# Load Testing

Load tests for the 4Runr Gateway using k6.

## Prerequisites

Install k6:
```bash
# macOS
brew install k6

# Linux
sudo gpg -k
sudo gpg --no-default-keyring --keyring /usr/share/keyrings/k6-archive-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys C5AD17C747E3415A3642D57D77C6C491D6AC1D69
echo "deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main" | sudo tee /etc/apt/sources.list.d/k6.list
sudo apt-get update
sudo apt-get install k6

# Windows
choco install k6
```

## Configuration

Set environment variables:
```bash
export GATEWAY_URL="http://localhost:3000"
export API_KEY="test-key-ce67dabb0d4e27e3d72877c921b89cae"
```

## Running Tests

### Basic Load Test
```bash
k6 run load-tests/k6-basic.js
```

### Rate Limit Test
```bash
k6 run load-tests/k6-rate-limit.js
```

### Custom Load Profile
```bash
# Edit the options in the test file, then run:
k6 run load-tests/k6-basic.js
```

## Test Scenarios

### Basic Load Test (`k6-basic.js`)
- Ramp up: 10 users over 30s
- Sustain: 10 users for 1m
- Peak: 50 users for 1m
- Ramp down: 0 users over 30s

Tests:
- Health checks
- List runs (read)
- Create runs (write)
- Get run (read)

### Rate Limit Test (`k6-rate-limit.js`)
- Rapid ramp up to 100 users
- Tests rate limiting enforcement
- Verifies rate limit error responses

## Metrics

k6 collects:
- Request duration (p95, p99)
- Error rate
- Rate limit hits
- Throughput (requests/second)

## Results

Results are output to:
- Console (summary)
- `load-test-results.json` (detailed metrics)

## Performance Targets

- **Response Time**: p95 < 500ms, p99 < 1s
- **Error Rate**: < 1%
- **Throughput**: Varies by endpoint

## Memory Leak Testing

Monitor memory usage during load tests:
```bash
# Run load test and monitor memory
k6 run load-tests/k6-basic.js &
PID=$!
while kill -0 $PID 2>/dev/null; do
  ps -p $PID -o rss=,vsz=,pcpu=
  sleep 5
done
```

## Notes

- Load tests should be run against a dedicated test environment
- Ensure PostgreSQL and Redis are available
- Monitor system resources during tests
- Adjust load profiles based on your infrastructure

