Module 15 — System Design & Behavioral

Nên có ⏱ 6-8 giờ 📋 Prerequisites: All previous modules

🎯 Mục tiêu học tập

📖 Hướng dẫn học

1 Đọc Mobile System Design resources
- github.com/nicehash/react-native-interview-questions
- Search "Mobile System Design" trên Medium/Dev.to
Thời gian: ~2h
2 Practice 3 system design questions
Viết ra giấy hoặc doc, vẽ diagram. Thời gian: ~2h
3 Prepare 5 STAR stories
Viết ra 5 tình huống thực tế từ kinh nghiệm. Thời gian: ~1h
4 Mock interview với bạn
Tập trả lời thành tiếng. Record lại nếu có thể. Thời gian: ~1-2h

⚡ Khung trả lời nhanh

  1. Clarify: user là ai, scale, offline cần không, security/compliance có gì đặc biệt?
  2. Scope: chốt MVP trước, nói rõ phần chưa design sâu.
  3. Architecture: screen/state/API/storage/sync/monitoring.
  4. Trade-off: vì sao chọn giải pháp này, đổi lại mất gì.
  5. Failure modes: mạng yếu, token hết hạn, conflict, crash, retry, rollout.

🧭 Vòng lặp học module này

📚 Lý thuyết chi tiết & System Design Questions

1. Design Offline-First Note-Taking App

Yêu cầu

Users tạo/sửa/xóa notes, sync across devices, hoạt động offline.

Key Decisions

Local Storage: WatermelonDB hoặc SQLite cho structured data, MMKV cho settings/metadata.

Sync Strategy:

Conflict Resolution:

Architecture:

UI Layer → Repository → Local DB (source of truth)
                      → Sync Engine → Remote API
                      
Sync Engine:
  - NetworkMonitor → trigger sync khi reconnect
  - OperationQueue → ordered mutations
  - ConflictResolver → merge/overwrite strategy

2. Design Push Notification System

End-to-end Flow

Backend                    Push Service              Device
   |                           |                        |
   |-- Send notification ---→ |                        |
   |   (FCM/APNs payload)     |                        |
   |                           |-- Deliver to device -→|
   |                           |                        |-- Display notification
   |                           |                        |-- User taps
   |                           |                        |-- Deep link → open screen

Key Components

3. Design Real-Time Chat App

Architecture

UI (FlatList inverted)
  ↕
Chat Store (Zustand/Redux)
  ↕
Message Service
  ├── WebSocket Client (real-time)
  ├── REST API (history, media upload)
  └── Offline Queue (pending messages)
  
Local DB: SQLite/WatermelonDB (message history cache)

Key Decisions

4. Design Authentication System

Token Flow

Login → Server returns {accessToken, refreshToken}
  ↓
accessToken: short-lived (15min), stored in memory
refreshToken: long-lived (30 days), stored in Keychain/Keystore
  ↓
API call → attach accessToken in Authorization header
  ↓
401 Unauthorized → use refreshToken to get new accessToken
  ↓
refreshToken expired → force logout

Key Decisions

5. Design Caching Strategy cho Media-Heavy App

Multi-layer Cache

Memory Cache (LRU, ~50 items)
  ↓ miss
Disk Cache (react-native-fast-image, ~500MB)
  ↓ miss
CDN / Remote Server

Key Decisions

6. Design State Management cho 20+ Screen App

Phân loại State

LoạiToolVí dụ
Local UI stateuseState, useReducerModal open, form input, tab active
Shared UI stateZustand storeTheme, user preferences, cart
Server stateReact QueryUser data, products, posts
Navigation stateReact NavigationScreen stack, deep link state
Auth stateContext + ZustandLogin status, tokens

Project Structure (Feature-based)

src/
├── features/
│   ├── auth/
│   │   ├── screens/
│   │   ├── hooks/
│   │   ├── api/
│   │   └── store/
│   ├── products/
│   ├── cart/
│   └── profile/
├── shared/
│   ├── components/
│   ├── hooks/
│   ├── utils/
│   └── api/
├── navigation/
└── app/

📚 Architecture Patterns

Feature-based vs Layer-based

Layer-basedFeature-based
Structurecomponents/, screens/, hooks/, api/features/auth/, features/products/
ScalabilityFolders phình to, khó tìm fileMỗi feature isolated, dễ navigate
Team workConflicts nhiều (edit cùng folder)Teams work on different features
RecommendationSmall apps (<10 screens)Medium-Large apps (10+ screens)

Clean Architecture (Simplified cho Mobile)

Presentation Layer (Screens, Components, ViewModels/Hooks)
        ↓
Domain Layer (Use Cases, Business Logic, Interfaces)
        ↓
Data Layer (Repositories, API clients, Local DB, DTOs)

Repository Pattern: Abstraction layer giữa data sources và business logic. Repository decide lấy data từ cache hay network, transform DTOs thành domain models.

📚 Behavioral Questions (STAR Method)

STAR = Situation → Task → Action → Result

Luôn trả lời theo format này. Cụ thể, có metrics nếu có.

Q1: Bug chỉ xảy ra trên production — approach?

Situation: Users report crash nhưng team không reproduce được trên dev.

Task: Tìm và fix bug, minimize user impact.

Action:

  1. Check Sentry/Crashlytics crash reports — stack trace, device info, OS version
  2. Check affected user segments (specific device? OS version? network?)
  3. Reproduce với production build (Hermes + release mode)
  4. Add remote logging nếu cần (không thể reproduce locally)
  5. Hotfix → CodePush/EAS Update nếu JS-only fix
  6. Post-mortem: add regression test, improve monitoring

Result: Fix deployed trong X giờ, crash rate giảm từ Y% xuống Z%.

Q2: App bị 1-star reviews vì crash — action plan?

Action plan:

  1. Triage: Sort crashes by frequency × severity. Top 3 crashes = priority
  2. Stability sprint: Dành 1 sprint focus 100% vào stability (no new features)
  3. Error boundaries: Wrap critical screens → graceful fallback thay vì crash
  4. Global error handler: Catch unhandled Promise rejections + JS exceptions
  5. Monitoring: Set alerts cho crash rate threshold
  6. Reply reviews: Acknowledge issue, promise fix timeline
  7. Regression tests: Add tests cho mỗi crash fix

Q3: Code review checklist?

  1. Correctness: Logic đúng? Edge cases handled?
  2. Performance: Re-renders unnecessary? Memory leaks? FlatList optimized?
  3. Security: Sensitive data exposed? Input validated?
  4. Types: TypeScript strict? No any? Proper null handling?
  5. Tests: New code có tests? Edge cases covered?
  6. Readability: Naming clear? Functions small? No magic numbers?
  7. Accessibility: Labels? Touch targets? Screen reader?
  8. Platform: Works on both iOS + Android?

Q4: Join team mới, codebase 50K+ LOC — onboarding?

Week 1: Đọc README, architecture docs. Setup project, run locally. Đọc PR history (understand conventions).

Week 2: Pick small bugs/tasks. Đọc code theo feature (follow 1 request end-to-end). Review PRs của teammates.

Week 3-4: Take on medium features. Pair program với senior. Document kiến thức mới (ADRs, wiki).

Key: Ask questions early. Không giả vờ hiểu. Document gaps cho future joiners.

Q5: Deadline tight, feature chưa xong — prioritize?

Approach:

  1. Communicate sớm với PM/stakeholders — không hide
  2. Break feature thành Must-have / Nice-to-have
  3. Negotiate scope: ship MVP first, iterate later
  4. Cut: animations, edge cases, advanced settings → tech debt ticket
  5. Increase: pair program, ask help, reduce meetings
  6. KHÔNG cut: tests cho critical flows, security, data integrity

❓ Câu hỏi phỏng vấn & Interview Tips

Ngày phỏng vấn

⚠️ Lỗi thường gặp khi trả lời

🏢 Case đi làm thật

Case: Interviewer hỏi design chat app. Câu trả lời chỉ nói WebSocket + FlatList + Redux nên bị thiếu chiều sâu.

Cách nâng cấp: Thêm message ordering, pending/offline queue, retry, local DB, pagination older messages, media upload, reconnect/backoff, push notification khi app background, delivery/read status và monitoring crash/log.

🧠 Ghi nhớ nhanh

System design mobile tốt không phải chọn nhiều tool. Điểm mạnh nằm ở requirement rõ, boundary rõ, trade-off rõ và biết app sẽ hỏng ở đâu khi vào production.

❔ Câu hỏi tự kiểm tra

1. Offline-first app cần lưu operation queue như thế nào để retry an toàn?
2. Chat app xử lý message pending, failed và duplicated ra sao?
3. Auth system cần làm gì khi refresh token bị revoke ở một thiết bị?
4. Behavioral story của bạn có Situation, Task, Action, Result rõ chưa?

✅ Checklist tự đánh giá

📎 Tài nguyên

📘 RN Interview Questions (GitHub)
📘 Tech Interview Handbook — Behavioral
📘 Mobile System Design Blog
📺 Search "Mobile System Design Interview" trên YouTube
📘 System Design Primer (GitHub)