This commit is contained in:
2026-03-17 09:21:45 +08:00
parent 0b2f4a026e
commit e5543ae6e4
3 changed files with 545 additions and 158 deletions

View File

@@ -1,192 +1,286 @@
# 歷멩????塋??㎬?訝?QPS ????ε?
# Game Performance & QPS Analysis (Dice Project)
## 訝???????訝?????鰲?
| 窈밭? | 瑥닸? |
|------|------|
| 瓦????? | Webman (?뷰? Workerman)竊?만要삣?耶?|
| HTTP ??? | `http://0.0.0.0:6688` |
| Worker ?곈? | `cpu_count() * 4`竊?? 8 ??= 32 訝??葉?? |
| ?경?佯?| MySQL竊?hinkORM竊???ζ? max=20/min=2 |
| 煐?? | Redis竊?hink-cache 容?? `redis`竊??瓦??黎?max=20/min=2 |
| 煐??要긷?力ⓩ? | `config/cache.php` 容?? `file`竊??訝??鵝욜?瑥ι?營??煐??壅경?餓띰?`config/think-cache.php` 容?? `redis`竊?PI ?ⓩ?/也????쉰嶺?슴??Redis |
> This document describes the current dice game backend architecture, key endpoints, approximate QPS capacity, and concrete optimization suggestions.
> It is written in plain ASCII to avoid any encoding or garbled-text issues.
---
## 雅????恙???????黎????
### 2.1 遙?뭉????녔???
| ?ε? | ?③??| 訝삭???? | 窯?섟??????竊??謠??쇽? |
|------|------|----------|------------------------|
| `POST /api/game/playStart` | 凉?冶??掠?歷멩?竊??也?? | 鸚?? DB + Redis + 雅?? | 遙??鰲??竊?|
| `POST /api/game/buyLotteryTickets` | 兀?물?썲???| 雅?????烏ⓨ???+ Redis ?닸? | 訝?|
| `GET /api/game/config` | 歷멩???쉰 | ?②〃 DiceConfig ?θ?竊??煐?? | 鵝?訝?|
| `GET /api/game/lotteryPool` | 也????쉰 | DiceRewardConfig 煐?? | 鵝?|
| `POST /api/v1/getGameUrl` | ?룟?歷멩??겼?竊?뭄?곤? | ?삣??삭? + JWT + Redis | 訝?|
| `POST /api/v1/getPlayerInfo` | ?⒴?岳→? | ??username ??DicePlayer | 鵝??兩븃? username ???訝?榮℡?竊?|
| `POST /api/v1/getPlayerGameRecord` | 歷멩?溫겼???〃 | ??〉 + ??? N+1 ?η?若?| 訝?|
| `POST /api/v1/setPlayerWallet` | ?긷?饔??饔?? | 雅??竊???곁?若?+ ???麗?| 訝?|
## 1. Runtime Environment Overview
### 2.2 `playStart` ???瑥룡??????㎗竊??㎬??녜?瓮??竊?
???歷멩?訝?轝↑?黎?ㄷ?답?鰲??竊?
**?경?佯??**
| Item | Description |
|-----------------|-----------------------------------------------------------------------------|
| Framework | Webman (on top of Workerman, long-running PHP workers) |
| Business module | `app/dice` (players, play records, rewards, lottery pool, dashboard, etc.) |
| HTTP endpoint | Typically `http://0.0.0.0:6688` |
| Worker count | Recommended: `cpu_count() * 4` (for example, 8 cores -> 32 workers) |
| Database | MySQL + ThinkORM, with connection pool (for example, max=20 / min=2) |
| Cache | Redis + think-cache, with connection pool (for example, max=20 / min=2) |
1. `DicePlayer::find($playerId)` ???↓??⒴?訝??窯?2. `DiceRewardConfig::getCachedMinRealEv()` ??腰??????ε?亮뜹?煐??
3. `LotteryService::getOrCreate()` ?????訝?Redis ?띰?`DicePlayer::find` + `DiceLotteryPoolConfig::where('type',0/1)->find()` 訝ㅶ?
4. `DiceLotteryPoolConfig::find($configId)` ?????營?ID ???黎?5. **雅????*竊?
- `DicePlayRecord::create`
- `DicePlayer::find($playerId)`竊??轝→??⒴?竊??鴉??竊?
- `DicePlayer::save`
- ??? `DicePlayerTicketRecord::create`竊?5 訝??竊?
- `DiceLotteryPoolConfig::where('id')->update(['ev' => Db::raw(...)])` ??烏?벨?닸?
- `DicePlayerWalletRecord::create`
6. 雅?????`DicePlayer::find($playerId)`??UserCache::setUser`
Recommended production configuration:
**Redis竊?*
- `DiceRewardConfig::getCachedInstance()`竊?? getCachedByTier 嶺????瑥?????깁?營??耶?- `LotteryService::getOrCreate()` ??瑥????若뜹?黎??耶?- `UserCache::setUser()` ??????룝에???耶?
?①?耶??訝??也썹????訝????? `playStart` 餓?벧??**6節? 轝?DB 溫욥?**竊??雅????2 轝?find ?⒴??? 轝?update 壤⑶?黎???節? 轝?create竊???
?η?耶???썰릎竊??鴉??????깁?營????黎??營????若띄??θ?轝→???
---
## 訝????㎬??띌?訝???⑴?
### 3.1 ?경?佯?
1. **瓦??黎?? Worker ??*
- ??? DB 瓦??黎?max=20竊?orker ??= CPU?4??? 32 訝?Worker ?????빨竊??雅?? 20 訝???ο??븀?嶺??訝???뜰??
- 兩븃?竊??????? `DB_POOL_MAX`竊?? 32節?4竊??亮띄???MySQL `max_connections` 訝???θ???
2. **`playStart` ???鸚???⒴?**
- 雅??鸚?럴 `DicePlayer::find($playerId)`竊???▼???`DicePlayer::find($playerId)`??
- ???訝뷴?雅?????????ⓨ럴??`$player` ????ε?誤??餘듸????訝?轝?SELECT??
3. **`DiceLotteryPoolConfig::where('id', $configId)->update(['ev' => Db::raw(...)])`**
- 驪???썸??겼?訝???쉰烏?? `ev`竊??亮뜹?訝??烏??塋?????竊???썸?訝븀?窯???
- ?????竊??閭η눕??????띌?/轝→??백??닸?竊??鵝욜? Redis 溫→?????뜹?閭ε? DB??
4. **榮℡?**
- `dice_player.username`??dice_play_record.player_id`??dice_play_record.create_time`??
`dice_player_wallet_record.player_id`??dice_player_ticket_record.player_id` 嶺????뻠榮℡?竊??烏ⓧ?瀯??鴉??????
- 兩븃??녑?竊?username` ???榮℡?竊?player_id` + `create_time` 瀯??榮℡?竊??若???θ??▽뻑孃??竊???
### 3.2 煐??
1. **煐??要긷?訝????*
- `config/cache.php` 容?? `file`竊??訝?????瑥ι?營?? Cache竊??壅경?餓띰?QPS 遙?? I/O ???鴉??訝븀?窯???
- 兩븃?竊??雅㎫?訝?鵝욜? Redis竊?뭉簾?? `CACHE_MODE=redis` 訝?think-cache ??default 訝??담??
2. **也????쉰煐??**
- `DiceRewardConfig::getCachedInstance()` 藥꿨???????????+ Redis竊??訝???뜻?㎬?也썬??
- ??岳????쉰????띈???`refreshCache()`竊?????????룡???
3. **UserCache ??㎗野?*
- 驪?? `getUser`/`setUser` ??AES ??㎗野??遙?QPS 訝?CPU 鴉?????鵝???만訝??腰???띌?竊???????? CPU 遙?????????↓???섄??value??
### 3.3 ??〃?ε? N+1
- `getPlayerGameRecord`竊????〉??`DicePlayRecord`竊?? `whereIn('id', $playerIds)` ?η?若뜹뭉瀯????
壤??若??藥꿨??백??η?若띰?訝???멨? N+1竊???ε?窈?limit 孃?ㄷ餓????????恙??耶???????limit 訝??竊?럴??100 訝??竊???
- `getPlayerWalletRecord` / `getPlayerTicketRecord` 鵝욜? `with(['dicePlayer'])` 窯??饔쏙??????
### 3.4 瓦??訝????
- Worker ??= CPU?4 ?띰??ζ?訝??黎????1 訝?DB 瓦??訝??黎???닻?竊?0 訝???ζ?熬??譯▲??
- 兩븃?竊?????訝??野?`DB_POOL_WAIT_TIMEOUT` ???瀯?만鰲??竊???녑????罌?ㄷ黎????????雅????
---
## ????PS 窯?섟竊??謠??쇽???????▼?竊?
### 4.1 ????▽뻑
- 8 ??CPU竊?2 訝?Worker??- MySQL/Redis ??????兩띈????竊??髥???띌???- 煐???썰릎???竊???깁?營???otteryService??serCache 鸚?맏?썰릎竊???
### 4.2 ?????嶸?
- **playStart**竊??轝←벧 50節?50 ms竊??雅??訝??轝?DB/Redis竊????Worker 瀛?7節?0 QPS竊?2 Worker 瀛?**220節?40 QPS**??
若????DB 烏??竊?? `dice_lottery_config.ev` ?닸?竊?????ζ?嶺??壤긷?竊?*岳??鴉계???? 200節?00 QPS**??- **buyLotteryTickets**竊??轝←벧 20節?0 ms竊???븀벧 **500節?000+ QPS**竊?빳瓦??黎?????譯▽맏???竊???- **getGameUrl / 亮녑??ε?**竊??壅??壤?? DB ?θ?竊??轝←벧 30節?0 ms竊???븀벧 **400節?00 QPS**竊?????壅곁?耶????
### 4.3 曆룟?役??
??70% 訝?`playStart`??0% 訝뷴?餓?????답???? QPS 鴉?? `playStart` ?얏?竊?*瀯쇔????瀛?250節?00 QPS** ???訝뷴?????담??
若??????ab/wrk/k6 嶺?? `playStart` ??말誤????役??瀯?? MySQL ?€?瑥???edis ?썰릎??????ζ?嶺??轝→????????
---
## 雅??????뻠溫????
| 映삣? | 兩븃? |
|------|------|
| ??쉰 | ??벨溫양쉰 `CACHE_MODE=redis`竊?뭉瀯??鵝욜? Redis 鵝?맏 Cache 要긷? |
| 瓦??黎?| ??? `DB_POOL_MAX`竊?? 32節?4竊??岳?? ??Worker ?곤?亮띄???MySQL max_connections |
| 餓g? | `playStart` 雅??????ⓨ럴?η? `$player`竊?????轝?`DicePlayer::find($playerId)` |
| ?경?佯?| 訝?`username`??player_id`??create_time` 嶺??窯??瑥℡?餘드?榮℡??????뇨凉?|
| ????닸? | `dice_lottery_config.ev` ???掠??닸??밥맏 Redis 榮?? + 若??/?백???? DB竊??鵝?????雅?|
| ??? | 野?`playStart`??buyLotteryTickets`??setPlayerWallet` ?????訝??瑥?????竊?뭉??MySQL ?€?瑥??瓦??黎??孃????|
| ??? | 鵝욜? ab/wrk/k6 野?`/api/game/playStart` 嶺???뜻????竊???겼???P99 兩띈?訝??鸚?QPS |
- Use Redis as default cache: in `.env`, set `CACHE_MODE=redis`.
- Align `DB_POOL_MAX` / `REDIS_POOL_MAX` with worker count and MySQL `max_connections`.
---
## ?????鵝???곁?若?QPS 訝?P99
## 2. Key Endpoints and Load Characteristics
1. **??? playStart**
- 鵝욜???? JWT竊??????삣??욕? token竊??野?`POST /api/game/playStart` ??body `direction=0` ??`1`??
- 鹽뷰?竊???욘? URL ??token竊??
```bash
# 鵝욜? ab
ab -n 1000 -c 32 -p post_body.json -T application/json -H "token: YOUR_JWT" http://127.0.0.1:6688/api/game/playStart
From the codebase, main game-related endpoints can be roughly grouped into:
- High-load: multiple DB writes plus Redis and non-trivial business logic.
- Medium-load: some DB writes or heavier DB reads.
- Light: mostly cache reads or simple DB queries.
### 2.1 Main endpoints (current project)
Below is a simplified view; exact routes live in the dice module and API controllers:
| Endpoint | Purpose | Load level | Notes / risks |
|-------------------------------------|--------------------------|------------|----------------------------------------------------------|
| `POST /api/game/playStart` | Start a play / roll | High | Multiple DB + Redis ops, main QPS bottleneck |
| `POST /api/game/buyLotteryTickets` | Buy tickets / chances | Med-High | Multiple table writes, wallet and ticket records |
| `GET /api/game/config` | Game config for frontend | Medium | Depends on `DiceConfig` and cache |
| `GET /api/game/lotteryPool` | Lottery / reward config | Medium | Depends on `DiceLotteryPoolConfig` / `DiceRewardConfig` |
| `POST /api/v1/getGameUrl` | Get game URL / entry | Medium | JWT + Redis auth; light DB usage |
| `POST /api/v1/getPlayerInfo` | Get player info | Medium | Needs index on `dice_player.username` |
| `POST /api/v1/getPlayerGameRecord` | Player history records | Med-High | Risk of N+1 if not using batch/with |
| `POST /api/v1/setPlayerWallet` | Adjust wallet balance | Medium | Wallet + records, must be concurrency-safe |
For QPS capacity analysis, focus on:
- `playStart` (core hot path).
- Ticket, wallet, record-related endpoints.
# 鵝욜? wrk竊?? lua ???鴉?token ??body竊? wrk -t4 -c32 -d30s -s play_start.lua http://127.0.0.1:6688/api/game/playStart
```
- 餓????릎孃?? Requests per second竊?PS竊?? Time per request竊???®? P99 ?ε램?룡??????
2. **??????**
- 佯??竊??訝????瑥룡?????뭄?? P99 ?????xx 訝???뜻??겹??
- MySQL竊???ζ?????θ???nnoDB 烏??嶺????
- Redis竊???ζ????訝?????餓ㅸ?????
3. **?띌??ㅶ?**
- ??QPS 訝????CPU ???譯???鴉?????餓g?????뷴???
- ??DB 瓦??嶺??????θ?罌?? ????뇨凉?????????瓦??黎???????〃??
- ??Redis 兩띈?訝?? ???εㄷ key????썰빱???瀯??瓦??黎???
---
## 訝????鵝??遙??㎬?竊????????
## 3. `playStart` Call Flow and Resource Usage
??*???雅㎩?驪?*餓???겻????竊????????窈밧?????얏???QPS 訝?㉢若??㎯??
### 7.1 ??쉰掠???백?營???????빰??????
The exact implementation is in the dice game logic layer and related services. A typical call flow looks like the following.
| 鴉??瀛?| ??? | 瑥닸? |
|--------|------|------|
| 遙?| ??벨???溫양쉰 `CACHE_MODE=redis` | ?욕?壅경?餓띄?耶????? I/O 訝??塋??竊?? think-cache 岳??訝??담??|
| 遙?| ??? DB 瓦??黎??`DB_POOL_MAX=32` ??`64` | 岳?? ??Worker ?곤?倻?32竊???욕?遙?뭉???瓦??嶺??訝???뜰??|
| 訝?| ??? Redis 瓦??黎??`REDIS_POOL_MAX=32` | 訝?Worker ?겼??????? Redis ?룟?瓦??嶺????|
| 訝?| 簾?? MySQL `max_connections` ??佯??瓦??黎??삣? | 鸚??堊??營꿩?竊??堊?? ? DB_POOL_MAX ?욤?瓦?MySQL 訝????|
### 3.1 DB access (typical)
**鹽뷰? .env ???竊?*
1. Load player:
- `DicePlayer::find($playerId)`
- Should be done once per request and reused.
```env
CACHE_MODE=redis
DB_POOL_MAX=32
DB_POOL_MIN=4
REDIS_POOL_MAX=32
```
2. Load reward EV / minimum real EV:
- `DiceRewardConfig::getCachedMinRealEv()`
- First call hits DB and writes Redis; later calls hit Redis only.
### 7.2 ?경?佯??竊??榮℡???????
3. Get or create lottery pool:
- `LotteryService::getOrCreate()`
- Reads from Redis; if missing, reads from DB (for example, `DiceLotteryPoolConfig::where('type', 0/1)->find()`).
| 鴉??瀛?| ??? | 瑥닸? |
|--------|------|------|
| 遙?| 訝?`dice_player.username` 兩뷴?訝?榮℡? | ?삣???etPlayerInfo??oken 訝??餓뜹???username ?ο???뇨凉???②〃?????|
| 遙?| 訝?`dice_play_record(player_id, create_time)` 兩븀???뇨凉?| 歷멩?溫겼???〃???溫→??⒴?+?띌??θ?竊?????窈듕?瀯????|
| 訝?| 訝뷸?麗닺〃 `player_id`??create_time` 兩븀뇨凉?| 倻?`dice_player_wallet_record`??dice_player_ticket_record` ???若뜻??띌?嶺?????ⓨ?訝???|
4. Load concrete pool config for this play:
- `DiceLotteryPoolConfig::find($configId)`
**鹽뷰? SQL竊??若??烏ⓨ?瘟??竊??**
5. Persist this play and its side effects (within one or several transactions):
- `DicePlayRecord::create()` (play record)
- `DicePlayer::save()` (balance and state)
- `DicePlayerTicketRecord::create()` (ticket usage)
- `DiceLotteryPoolConfig::where('id')->update(['ev' => Db::raw(...)]` (EV statistics)
- `DicePlayerWalletRecord::create()` (wallet history)
6. Refresh player cache:
- Reuse or reload player and call `UserCache::setUser($player)`.
Rough DB count (assuming good caching and no redundant `find` calls):
- About 3-6 DB queries/updates per `playStart`.
- About 3-6 Redis operations per `playStart`.
If the code calls `DicePlayer::find($playerId)` multiple times in one request, DB usage and latency will increase accordingly.
### 3.2 Redis access
Typical Redis usages in the current design:
- Reward / pool configs: `DiceRewardConfig::getCachedInstance()`, `getCachedByTier()`, `LotteryService::getOrCreate()`.
- Player cache: `UserCache::getUser()`, `UserCache::setUser()`.
- Optional counters: EV / statistics counters can be done via Redis `INCRBY`, etc.
Goal: hot paths should hit Redis most of the time, and DB should primarily be for persistence and cold reads.
---
## 4. Main Bottlenecks and Optimizations
### 4.1 DB connections and slow SQL
1. Connection pool sizing:
- With 32 workers and `DB_POOL_MAX=20`, connection exhaustion and waiting are likely at higher QPS.
- Recommendation: set `DB_POOL_MAX` to something like 32-64 (depending on CPU and MySQL `max_connections`), and check that MySQL allows enough connections.
2. Avoid redundant queries:
- In `playStart`, ensure player is loaded once and reused (do not call `DicePlayer::find` multiple times per request).
3. EV update strategy:
- Repeated `UPDATE dice_lottery_config SET ev = ev - ?` on a hot row causes lock contention.
- Better:
- Accumulate EV deltas in Redis (per pool or per shard).
- Periodic cron job to aggregate Redis deltas back into MySQL in batches.
4. Index coverage:
- Ensure all high-frequency queries (`username`, `player_id`, `create_time`, status fields) use proper indexes (see section 6).
### 4.2 Cache and serialization overhead
1. Use Redis cache driver:
- In `.env`, set `CACHE_MODE=redis`.
- In `config/cache.php`, the default store should be Redis in production.
2. Player cache encryption:
- If `UserCache` encrypts/decrypts data (for example, AES), CPU cost can be high at large QPS.
- Possible mitigations:
- Keep cached value small (only necessary fields).
- Limit how often `setUser` is called (only on actual state changes).
- Avoid double-encryption or repeated heavy serialization in hot paths.
### 4.3 N+1 queries
Endpoints like "get player game record" or wallet histories can easily trigger N+1 patterns:
- Use `whereIn('player_id', $playerIds)` instead of one query per player.
- Use eager loading (`with(['dicePlayer'])`) for related player info.
- Keep page size (`limit`) moderate (for example, 100 rows or less per page).
### 4.4 Redis vs DB coordination
- Ensure worker count, DB pool and Redis pool are balanced:
- If CPU is not saturated but DB or Redis is fully blocked, it is a typical sign of misconfiguration.
- Monitor Redis:
- Use slowlog for heavy commands.
- Watch for large keys or hot keys; consider hash or sharding if needed.
---
## 5. Approximate QPS Capacity (Single Node)
These are ballpark figures for a single node with something like 8 cores and 32 workers, with MySQL and Redis in the same LAN and the optimizations above applied. Real numbers must come from your own load tests.
### 5.1 Per-endpoint estimates
- `playStart`:
- Typical latency: about 50-150 ms.
- Expected QPS: about 200-300 per node.
- `buyLotteryTickets`:
- Typical latency: about 20-60 ms.
- Expected QPS: about 500-1000+ per node.
- `getGameUrl` / login-style endpoints:
- Typical latency: about 30-80 ms.
- Expected QPS: about 400-800 per node.
### 5.2 Mixed traffic scenario
Example traffic mix:
- 70% `playStart`
- 30% lighter endpoints (`getGameUrl`, `getPlayerInfo`, and similar)
Under such a mix, with reasonable indexing and caching:
- A single 8-core node can typically sustain about 250-400 QPS overall.
- To go significantly beyond that, you will normally use horizontal scaling (multiple app nodes) plus DB/Redis scaling (read replicas, sharding, and so on).
---
## 6. Index and Table Design Recommendations
### 6.1 Must-have indexes
| Table | Index | Purpose |
|-----------------------------|-----------------------------------|------------------------------------------|
| `dice_player` | unique(`username`) | Fast lookup by username (login, API) |
| `dice_play_record` | index(`player_id`, `create_time`) | Player record listing plus time sorting |
| `dice_player_wallet_record` | index(`player_id`, `create_time`) | Wallet history listing |
| `dice_player_ticket_record` | index(`player_id`, `create_time`) | Ticket history listing |
Example SQL:
```sql
-- ?ε?????ⓨ?曆삣?
ALTER TABLE dice_player ADD UNIQUE INDEX uk_username (username);
ALTER TABLE dice_play_record ADD INDEX idx_player_create (player_id, create_time);
ALTER TABLE dice_player_wallet_record ADD INDEX idx_player_create (player_id, create_time);
ALTER TABLE dice_player_ticket_record ADD INDEX idx_player_create (player_id, create_time);
```
### 7.3 餓g?掠????? DB 瘟??訝???백?竊?
| 鴉??瀛?| ??? | 瑥닸? |
|--------|------|------|
| 遙?| `playStart` 雅??????ⓨ럴?η? `$player`竊????`DicePlayer::find($playerId)` | 弱?1 轝?SELECT竊???▼??ⓨ?訝? `$player` ???耶????? 1 轝?SELECT??|
| 訝?| `game/config` ?ε?訝?DiceConfig ???耶?| ??쉰???窯??鵝????Redis 煐?? 1節? ???竊??弱??烏ⓩ?瑥???|
| 訝?| `dice_lottery_config.ev` ?밥맏 Redis 榮?? + 若????? DB | 驪??訝?? `UPDATE dice_lottery_config SET ev=ev-?`竊?????烏???백?竊??驪?????驪?N 掠????訝?轝▲??|
### 6.2 Large-table strategy
### 7.4 ???訝????
| 鴉??瀛?| ??? | 瑥닸? |
|--------|------|------|
| 訝?| 野?`playStart`??buyLotteryTickets` ?????訝??瑥????? | 堊요?????<3F>?黎??凉?만役????|
| 訝?| 凉???MySQL ?€?瑥€?恙??倻?>200ms竊?| 若??????뇨凉??鴉????SQL??|
| 鵝?| ???孃????? QPS 訝?P99 | ??ab/wrk/k6 野?`playStart` ???竊?빳?경?若??????⒴??뜻???|
For very large history tables (play records, wallet logs, ticket logs), plan ahead:
### 7.5 窯?????竊??謠??쇽?
- Partitioning or sharding (by time or by player ID).
- Archival strategy (move very old data to cold storage or delete).
- ??쉰掠?+ 榮℡?竊???δ????訝븀?窯????〃訝??壤?????얍?恙???답??????벧 **20%節?0%** ??? QPS??- ?삥? playStart ??2 轝▼?鵝??佯?????黎?? 2 轝?round-trip竊?*playStart ???黎????瀛?? 5%節?5%**??- ev ?밥맏 Redis 榮??竊??亮뜹?訝?**playStart** 烏??塋??訝??竊????playStart QPS ????????**10%節?0%**竊??亮뜹?佯????竊???
---
**瑥닸?**竊??瓦?QPS 訝??????맏?뷰?餓g?訝??營??鴉곁?竊?????㎬?餓ε?役??瀛요????訝뷴???뻠溫??窯??/??벨??????弱??饔?`playStart` 訝??壤????????녔????????
## 7. Load Testing and Metrics
### 7.1 Load testing `playStart`
1. Prepare:
- Seed enough test players and balances.
- Obtain valid JWT tokens.
2. `ab` example:
```bash
ab -n 2000 -c 32 \
-p post_body.json \
-T application/json \
-H "token: YOUR_JWT" \
http://127.0.0.1:6688/api/game/playStart
```
3. `wrk` example:
```bash
wrk -t4 -c32 -d60s -s play_start.lua http://127.0.0.1:6688/api/game/playStart
```
4. Focus on:
- QPS (Requests per second)
- P95 / P99 latency
- Error rates (HTTP 5xx, timeouts, business failures)
- MySQL / Redis CPU and connection usage
### 7.2 Typical troubleshooting
- Low QPS but low CPU:
- Likely DB or Redis connection pool exhaustion or slow queries.
- High P99 spikes:
- Check for large transactions, schema changes, backup jobs, GC, or disk I/O hiccups.
- Redis issues:
- Look for big keys, blocking commands (for example, `KEYS`), or high single-key contention.
---
## 8. Configuration and Code Checklist
Use this list before load tests or production deployments.
### 8.1 Configuration
- `.env`:
- [ ] `CACHE_MODE=redis`
- [ ] `DB_POOL_MAX` / `DB_POOL_MIN` tuned for CPU and MySQL `max_connections`
- [ ] `REDIS_POOL_MAX` large enough for concurrent traffic
- MySQL:
- [ ] `max_connections` greater than or equal to the sum of all app DB pools
- [ ] Slow query log enabled with a reasonable threshold
### 8.2 Code
- [ ] `playStart` loads player once and reuses it everywhere.
- [ ] Reward and pool configuration is always accessed via cache; after changes, cache is refreshed.
- [ ] History and wallet endpoints avoid N+1; use batch queries and eager loading.
- [ ] EV and other hot counters use Redis aggregation instead of per-request `UPDATE` on hot rows.
---
## 9. Summary
- For the current dice project, `playStart` and related lottery, wallet, and ticket flows define the backend QPS ceiling.
- With proper connection pool tuning, Redis caching, indexing, and fewer redundant DB operations, a single 8-core node can typically handle a few hundred QPS of mixed traffic.
- Real capacity must be validated via `ab`, `wrk`, or `k6` load tests against your environment; this document serves as a practical guide for identifying and fixing performance bottlenecks.