# K6 Load Testing Documentation for GoodGo Platform

Complete guide to understanding and implementing K6 load tests for the GoodGo Platform API.

---

## 📚 Documentation Files

This directory contains three comprehensive guides for K6 load testing:

### 1. **K6_LOAD_TESTING_GUIDE.md** (Primary Reference)
Comprehensive exploration of the GoodGo Platform API structure for load testing.

**Contents:**
- API module structure (auth, listings, payments, search)
- Detailed endpoint documentation with HTTP methods, rate limits, and auth requirements
- Complete DTO specifications with request/response body shapes
- Database and environment configuration reference
- Existing test setup (Playwright, Vitest, CI/CD)
- Architecture patterns (CQRS, DDD)
- File location quick reference
- K6 implementation recommendations

**When to use:** Deep dives into specific endpoints, understanding authentication flows, checking environment variables

### 2. **K6_ENDPOINTS_SUMMARY.md** (Quick Reference)
Condensed endpoint reference with data shapes for immediate lookup.

**Contents:**
- All endpoints in table format (method, path, auth, rate limit)
- Authentication module (register, login, refresh, profile)
- Listings module (CRUD, moderation, media upload)
- Payments module (create, list, callbacks, refund)
- Search module (full-text, geo)
- Request/response body examples (JSON)
- K6 test scenarios (search, auth, listings, payments, webhooks)
- Rate limits summary
- Authentication flow examples (cookies vs tokens)

**When to use:** Quick lookup of endpoint details, copy-paste example payloads, understanding rate limits

### 3. **K6_QUICK_START.md** (Executable Examples)
Step-by-step guide with ready-to-run K6 scripts and setup instructions.

**Contents:**
- Installation instructions (macOS, Linux, Docker)
- Environment setup (starting API, seeding database)
- Five runnable K6 scripts:
  - Search load test (public, high volume)
  - Auth load test (rate-limited registration)
  - Listing creation (authenticated, quota-gated)
  - Payment processing (authenticated)
  - All scenarios combined
- CI integration with GitHub Actions
- Report generation options (JSON, Grafana Cloud, CSV)
- Common K6 checks and patterns
- Debugging and troubleshooting

**When to use:** Getting started quickly, running tests immediately, setting up CI/CD

---

## 🚀 Quick Start (3 Minutes)

### 1. Install K6
```bash
brew install k6  # macOS
# or
apt-get install k6  # Linux
```

### 2. Start API & Database
```bash
pnpm install
pnpm db:generate
pnpm db:migrate:dev
pnpm db:seed
pnpm dev
```

### 3. Run a Load Test
```bash
# Copy this from K6_QUICK_START.md Step 3
k6 run load-tests/search.k6.js
```

### 4. View Results
K6 prints a summary to console. For more detailed reports, see K6_QUICK_START.md section on report generation.

---

## 📊 Test Scenarios Implemented

| Scenario | File | Focus | VUs | Duration | Key Endpoints |
|----------|------|-------|-----|----------|--------------|
| Search Load | `load-tests/search.k6.js` | Public search performance | 50 | 4m | `GET /search`, `GET /search/geo` |
| Authentication | `load-tests/auth.k6.js` | Auth throughput & rate limits | 10 | 2m | `POST /auth/register`, `POST /auth/login` |
| Listing Creation | `load-tests/listings.k6.js` | Authenticated listing CRUD | 5 | 2m | `POST /listings`, `GET /listings/:id` |
| Payments | `load-tests/payments.k6.js` | Payment initiation & status | 10 | 2m | `POST /payments`, `GET /payments/:id` |
| Combined | `load-tests/all-scenarios.k6.js` | Realistic mixed load | 50 | 5m | Multiple endpoints |

---

## 🔐 Authentication Methods

### Option 1: Cookie-Based (Recommended for Browser-Like Tests)
```javascript
const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password });
// Cookies automatically managed by K6
const profileRes = http.get(`${BASE_URL}/auth/profile`);
```

### Option 2: Bearer Token (Recommended for API-Only Tests)
```javascript
const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password });
const { accessToken } = loginRes.json();
const headers = { Authorization: `Bearer ${accessToken}` };
const profileRes = http.get(`${BASE_URL}/auth/profile`, { headers });
```

See K6_ENDPOINTS_SUMMARY.md for full examples.

---

## 🎯 Key Endpoints by Priority

### High Priority (Core Functionality)
| Endpoint | Priority | Why |
|----------|----------|-----|
| `GET /search` | ⭐⭐⭐ | Public, high-volume query |
| `GET /search/geo` | ⭐⭐⭐ | Geospatial, frequently used |
| `GET /listings` | ⭐⭐⭐ | Public search/filter |
| `GET /listings/:id` | ⭐⭐⭐ | Detail page load |
| `POST /auth/login` | ⭐⭐ | User session creation |
| `POST /auth/register` | ⭐⭐ | Rate-limited, important |

### Medium Priority (Feature-Specific)
| Endpoint | Priority | Why |
|----------|----------|-----|
| `POST /listings` | ⭐⭐ | Quota-gated, authenticated |
| `POST /payments` | ⭐⭐ | External integrations |
| `GET /payments` | ⭐⭐ | User transaction history |
| `POST /payments/callback/:provider` | ⭐⭐ | Webhook handler, critical |

### Low Priority (Admin/Specialized)
| Endpoint | Priority | Why |
|----------|----------|-----|
| `PATCH /listings/:id/moderate` | ⭐ | Admin-only |
| `GET /listings/pending` | ⭐ | Admin-only |
| `POST /search/reindex` | ⭐ | Admin-only, scheduled |

---

## 📍 API Structure at a Glance

```
API Base: http://localhost:3001/api/v1

Modules:
├── /auth               # User authentication & profiles
├── /listings           # Property CRUD & moderation
├── /search             # Full-text & geo search
├── /payments           # Payment processing & webhooks
├── /subscriptions      # Plans & quotas (not focused for load tests)
├── /admin              # Admin operations (low priority for load tests)
└── /analytics          # Market data (low priority for load tests)
```

---

## 🗄️ Database Configuration

### Local Development
```bash
DATABASE_URL=postgresql://goodgo:password@localhost:5432/goodgo
REDIS_URL=redis://localhost:6379
TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
```

### Test Environment (CI)
```bash
DATABASE_URL=postgresql://goodgo:goodgo_test_secret@localhost:5432/goodgo_test
REDIS_URL=redis://localhost:6379
TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
```

See K6_LOAD_TESTING_GUIDE.md for full environment variables.

---

## ⚡ Rate Limits

Respect these limits in your load tests:

| Endpoint | Limit | Window | Action on Exceeded |
|----------|-------|--------|-------------------|
| `/auth/register` | 5 | per hour | Returns 429 |
| `/auth/login` | 5 | per hour | Returns 429 |
| `/auth/refresh` | 5 | per hour | Returns 429 |
| `/payments/callback/*` | 20 | per minute | Returns 429 |
| All others | None | N/A | Quota gates apply for writes |

**K6 Handling:**
```javascript
check(res, {
  'status not rate limited': (r) => r.status !== 429,
  'status success or expected': (r) => [200, 201, 400, 404].includes(r.status),
});
```

---

## 🏗️ Recommended Test Structure

```
load-tests/
├── search.k6.js              # High-volume public search
├── auth.k6.js                # Authentication flow with rate limit handling
├── listings.k6.js            # Authenticated listing creation
├── payments.k6.js            # Payment processing
├── all-scenarios.k6.js       # Combined realistic mix
├── helpers/
│   ├── data-generators.js    # Generate test data (users, listings)
│   ├── auth-flows.js         # Reusable login/register functions
│   └── assertions.js         # Custom check functions
└── config.js                 # Base URL, env, thresholds
```

Example helper structure provided in K6_QUICK_START.md.

---

## 🧪 Integration with Existing Tests

### Complement, Don't Replace

K6 is for **load testing** (performance under concurrent load).
Existing tests serve different purposes:

| Test Type | Tool | Purpose | When |
|-----------|------|---------|------|
| Unit Tests | Vitest | Verify function logic | During development |
| E2E Tests | Playwright | Verify user flows work | Before deployment |
| Load Tests | K6 | Verify performance at scale | Scheduled, on-demand |

### Running All Tests

```bash
# Unit tests (API only)
pnpm test

# E2E tests (API + Web)
pnpm test:e2e

# Load tests (new)
k6 run load-tests/search.k6.js

# All in sequence
pnpm test && pnpm test:e2e && k6 run load-tests/all-scenarios.k6.js
```

---

## 📈 CI/CD Integration

### GitHub Actions Workflow

Create `.github/workflows/load-test.yml` (template in K6_QUICK_START.md section 🔟):

```bash
# Runs on schedule (daily at 2 AM)
# Or manually via workflow_dispatch
# Reports results as artifacts
```

### Manual Reporting

```bash
# Export JSON
k6 run load-tests/search.k6.js --summary-export=results.json

# View CSV (with extension)
k6 run load-tests/search.k6.js --out csv=results.csv

# Upload to Grafana Cloud
K6_CLOUD_TOKEN=xxx k6 run load-tests/search.k6.js --out cloud
```

---

## 🔗 Cross-Reference Guide

### Looking for...?

| Need | Find in |
|------|----------|
| All endpoint URLs & methods | K6_ENDPOINTS_SUMMARY.md |
| Request/response JSON shapes | K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes) |
| DTOs & validation rules | K6_LOAD_TESTING_GUIDE.md (Controllers & DTOs) |
| Rate limit specifics | K6_ENDPOINTS_SUMMARY.md (📌 Important Rate Limits) |
| Authentication flows | K6_ENDPOINTS_SUMMARY.md (🔗 Authentication Flow for K6) |
| Database variables | K6_LOAD_TESTING_GUIDE.md (🗄️ Database & Environment) |
| Ready-to-run scripts | K6_QUICK_START.md (Steps 3-8️⃣) |
| CI/CD setup | K6_QUICK_START.md (Step 🔟) |
| Troubleshooting | K6_QUICK_START.md (✅ Troubleshooting) |
| Architecture details | K6_LOAD_TESTING_GUIDE.md (📊 Architecture Patterns) |
| File locations | K6_LOAD_TESTING_GUIDE.md (📁 File Locations Quick Reference) |

---

## 🛠️ Common Tasks

### Task: Load Test Search Endpoint
1. Read: K6_ENDPOINTS_SUMMARY.md (🔍 Search section)
2. Use: K6_QUICK_START.md (Step 3️⃣ - Search Load Test)
3. Run: `k6 run load-tests/search.k6.js`

### Task: Understand Payment Flow
1. Read: K6_LOAD_TESTING_GUIDE.md (💳 PAYMENTS MODULE)
2. Check: K6_ENDPOINTS_SUMMARY.md (💳 Payments section)
3. Use: K6_QUICK_START.md (Step 7️⃣ - Payment Test)

### Task: Add New Endpoint to Load Tests
1. Find endpoint in: K6_LOAD_TESTING_GUIDE.md or K6_ENDPOINTS_SUMMARY.md
2. Get data shape from: K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes)
3. Check auth from: K6_LOAD_TESTING_GUIDE.md (each module section)
4. Implement using examples in: K6_QUICK_START.md

---

## ✅ Verification Checklist

Before running load tests, verify:

- [ ] API running: `pnpm dev` (port 3001)
- [ ] Database seeded: `pnpm db:seed`
- [ ] K6 installed: `k6 version`
- [ ] Can reach API: `curl http://localhost:3001/api/v1/docs`
- [ ] ENV variables set: `JWT_SECRET`, `CORS_ORIGINS`, etc.
- [ ] Load test file exists: `load-tests/*.k6.js`
- [ ] Test data available: Check seed in `prisma/seed.ts`

---

## 📞 Support & References

### Internal Documentation
- **Full Architecture**: K6_LOAD_TESTING_GUIDE.md
- **Endpoint Reference**: K6_ENDPOINTS_SUMMARY.md
- **Getting Started**: K6_QUICK_START.md

### External Resources
- **K6 Official Docs**: https://k6.io/docs
- **K6 API Reference**: https://k6.io/docs/javascript-api
- **K6 Community**: https://community.k6.io
- **K6 Examples**: https://github.com/grafana/k6-templates

### Project Files
- **API Controllers**: `apps/api/src/modules/*/presentation/controllers/`
- **DTOs**: `apps/api/src/modules/*/presentation/dto/`
- **E2E Tests**: `e2e/api/`
- **Seed Data**: `prisma/seed.ts`

---

## 🎓 Learning Path

### Beginner (30 minutes)
1. Read K6_QUICK_START.md (Steps 1-4)
2. Install K6
3. Run: `k6 run load-tests/search.k6.js`

### Intermediate (1-2 hours)
1. Read K6_ENDPOINTS_SUMMARY.md
2. Understand auth flows
3. Run auth test: `k6 run load-tests/auth.k6.js`
4. Run listing test: `k6 run load-tests/listings.k6.js`

### Advanced (2-4 hours)
1. Read K6_LOAD_TESTING_GUIDE.md completely
2. Review controller implementations in source
3. Create custom load test script
4. Set up CI/CD with GitHub Actions (K6_QUICK_START.md Step 🔟)
5. Generate and analyze reports

---

## 📝 Notes

- **No existing K6 setup** — These docs provide complete guidance
- **Three complementary docs** — Explore different docs for different needs
- **Executable examples** — K6_QUICK_START.md scripts work as-is
- **Rate limits matter** — Consider them in test design
- **Quota gates** — Some operations (listings, payments) are gated by subscription
- **Test data** — Use seed data or generate unique test users per VU
- **Production ready** — Guides follow K6 best practices

---

Generated: 2026-04-09
Last Updated: K6_QUICK_START.md latest

