Skip to content

Commit 6ba5744

Browse files
committed
feat: add comprehensive Sentry monitoring and fix 429 rate limiting error
1 parent 862e580 commit 6ba5744

File tree

13 files changed

+3704
-367
lines changed

13 files changed

+3704
-367
lines changed

Dockerfile

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ RUN pnpm install --frozen-lockfile --prod
3838

3939
# Copy built application from builder stage
4040
COPY --from=builder /app/dist ./dist
41+
COPY newrelic.js ./
42+
43+
# Set New Relic environment variables
44+
ENV NEW_RELIC_NO_CONFIG_FILE=false
45+
ENV NEW_RELIC_DISTRIBUTED_TRACING_ENABLED=true
46+
ENV NEW_RELIC_LOG=stdout
47+
ENV NEW_RELIC_LOG_LEVEL=info
4148

4249
# Change ownership to non-root user
4350
RUN chown -R typelets:nodejs /app

README.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ The backend API for the [Typelets Application](https://github.com/typelets/typel
2222
-**Fast & Type-Safe** with TypeScript and Hono
2323
- 🐘 **PostgreSQL** with Drizzle ORM
2424
- 💻 **Code Execution** via secure Judge0 API proxy
25+
- 📊 **Performance Monitoring** with New Relic APM
2526

2627
## Tech Stack
2728

@@ -30,6 +31,7 @@ The backend API for the [Typelets Application](https://github.com/typelets/typel
3031
- **Database**: PostgreSQL with [Drizzle ORM](https://orm.drizzle.team/)
3132
- **Authentication**: [Clerk](https://clerk.com/)
3233
- **Validation**: [Zod](https://zod.dev/)
34+
- **Monitoring**: [New Relic](https://newrelic.com/) for APM and error tracking
3335
- **TypeScript**: Strict mode enabled for type safety
3436

3537
## Prerequisites
@@ -39,6 +41,7 @@ The backend API for the [Typelets Application](https://github.com/typelets/typel
3941
- PostgreSQL database (local installation or Docker)
4042
- Clerk account for authentication ([sign up here](https://dashboard.clerk.com))
4143
- Judge0 API key for code execution (optional - [get from RapidAPI](https://rapidapi.com/judge0-official/api/judge0-ce))
44+
- New Relic account for monitoring (optional - [sign up here](https://newrelic.com/signup))
4245

4346
## Local Development Setup
4447

@@ -74,13 +77,16 @@ cp .env.example .env
7477
- Create a free account at [Clerk Dashboard](https://dashboard.clerk.com)
7578
- Create a new application
7679
- (Optional) Get Judge0 API key from [RapidAPI](https://rapidapi.com/judge0-official/api/judge0-ce)
80+
- (Optional) Get New Relic license key from [New Relic Dashboard](https://one.newrelic.com/launcher/api-keys-ui.api-keys-launcher)
7781
- Update `.env` with your settings:
7882

7983
```env
8084
CLERK_SECRET_KEY=sk_test_your_actual_clerk_secret_key_from_dashboard
8185
CORS_ORIGINS=http://localhost:5173,http://localhost:3000
8286
# Optional: For code execution features
8387
JUDGE0_API_KEY=your_judge0_rapidapi_key_here
88+
# Optional: For performance monitoring and error tracking
89+
NEW_RELIC_LICENSE_KEY=your_new_relic_license_key_here
8490
```
8591

8692
5. **Set up database schema:**
@@ -255,6 +261,54 @@ The application uses the following main tables:
255261
- **WebSocket Security**: JWT authentication, rate limiting, and connection limits
256262
- **Real-time Authorization**: Database-level ownership validation for all WebSocket operations
257263

264+
## Performance Monitoring
265+
266+
The API includes comprehensive monitoring via New Relic APM for production observability and performance optimization.
267+
268+
### Monitoring Features
269+
270+
- **Application Performance Monitoring (APM)**: Real-time performance metrics for HTTP requests, database queries, and external API calls
271+
- **Error Tracking**: Automatic error detection and alerting with detailed stack traces
272+
- **Custom Events**: Application startup, user authentication, and business logic events
273+
- **Transaction Tracing**: Detailed breakdown of slow requests and database operations
274+
- **Infrastructure Monitoring**: Server resources, memory usage, and system health
275+
276+
### Environment-Specific Monitoring
277+
278+
**Development Environment:**
279+
- App Name: `typelets-api-dev`
280+
- Debug-level logging with detailed instrumentation
281+
- Lower performance thresholds for early issue detection
282+
- Enhanced error collection and context
283+
284+
**Production Environment:**
285+
- App Name: `typelets-api-prod`
286+
- Optimized logging for performance
287+
- High-security mode with sensitive data filtering
288+
- Production-tuned sampling rates
289+
290+
### Monitored Operations
291+
292+
- **HTTP Requests**: All API endpoints with response times and status codes
293+
- **Database Queries**: PostgreSQL operations with query performance tracking
294+
- **External APIs**: Judge0 API calls with latency and error monitoring
295+
- **WebSocket Operations**: Real-time connection management and message processing
296+
- **File Operations**: Upload/download performance and error tracking
297+
298+
### New Relic Dashboard Access
299+
300+
Once configured, monitor your application at:
301+
- Development: Search for `typelets-api-dev` in your New Relic dashboard
302+
- Production: Search for `typelets-api-prod` in your New Relic dashboard
303+
304+
### Custom Monitoring
305+
306+
The application sends custom events for business intelligence:
307+
- `ApplicationStartup`: Server initialization with configuration details
308+
- User authentication events with performance metrics
309+
- Slow operation alerts (configurable thresholds)
310+
- Resource usage patterns and scaling indicators
311+
258312
## Environment Variables
259313

260314
| Variable | Description | Required | Default |
@@ -274,8 +328,13 @@ The application uses the following main tables:
274328
| `WS_MAX_CONNECTIONS_PER_USER`| Max WebSocket connections per user | No | 20 |
275329
| `WS_AUTH_TIMEOUT_MS` | WebSocket authentication timeout in milliseconds | No | 30000 (30 sec) |
276330
| `JUDGE0_API_KEY` | Judge0 API key for code execution | No* | - |
331+
| `NEW_RELIC_LICENSE_KEY` | New Relic license key for APM monitoring | No** | - |
332+
| `NEW_RELIC_APP_NAME` | Custom New Relic application name | No | Auto-generated |
333+
| `NEW_RELIC_LOG` | New Relic log output (stdout/stderr/filepath) | No | stdout (dev) / file (prod) |
334+
| `NEW_RELIC_LOG_LEVEL` | New Relic logging level (error/warn/info/debug/trace) | No | debug (dev) / info (prod) |
277335

278336
*Required only for code execution features
337+
**Required only for performance monitoring and error tracking
279338

280339
## Development
281340

@@ -334,6 +393,14 @@ docker build -t typelets-api .
334393

335394
# 3. Run API container for local testing
336395
docker run -p 3000:3000 --env-file .env typelets-api
396+
397+
# Or with explicit New Relic configuration
398+
docker run -p 3000:3000 \
399+
-e NEW_RELIC_LICENSE_KEY=your_license_key_here \
400+
-e NEW_RELIC_APP_NAME="typelets-api-dev" \
401+
-e NODE_ENV=development \
402+
--env-file .env \
403+
typelets-api
337404
```
338405

339406
**This Docker setup is for local development and testing only.**
@@ -367,6 +434,25 @@ This application is designed for production deployment using AWS ECS (Elastic Co
367434

368435
For production deployment, configure the same environment variables in your ECS task definition that you use locally in `.env`.
369436

437+
### Production Monitoring Setup
438+
439+
For production deployments, ensure New Relic monitoring is properly configured:
440+
441+
```bash
442+
# Example production environment variables in ECS task definition
443+
NODE_ENV=production
444+
NEW_RELIC_LICENSE_KEY=your_production_license_key
445+
NEW_RELIC_APP_NAME=typelets-api-prod
446+
NEW_RELIC_LOG=stdout
447+
NEW_RELIC_LOG_LEVEL=info
448+
```
449+
450+
This will automatically:
451+
- Enable production-optimized monitoring settings
452+
- Filter sensitive data from logs and traces
453+
- Set appropriate sampling rates for production scale
454+
- Create separate application monitoring (dev vs prod)
455+
370456
## Contributing
371457

372458
We welcome contributions from the community!

newrelic.js

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
'use strict';
2+
3+
const isDevelopment = process.env.NODE_ENV === 'development';
4+
const isProduction = process.env.NODE_ENV === 'production';
5+
6+
// Debug logging for configuration
7+
console.log('🔧 New Relic Config Loading...');
8+
console.log(` Environment: ${process.env.NODE_ENV || 'development'}`);
9+
console.log(` License Key: ${process.env.NEW_RELIC_LICENSE_KEY ? 'Set' : 'Using default'}`);
10+
console.log(` Development Mode: ${isDevelopment}`);
11+
12+
/**
13+
* New Relic agent configuration.
14+
*/
15+
exports.config = {
16+
// Environment-specific app naming
17+
app_name: [
18+
isDevelopment ? 'typelets-api-dev' :
19+
isProduction ? 'typelets-api-prod' :
20+
'typelets-api-staging'
21+
],
22+
23+
license_key: process.env.NEW_RELIC_LICENSE_KEY,
24+
25+
// Environment-specific logging configuration
26+
logging: {
27+
level: isDevelopment ? 'debug' : 'info',
28+
filepath: process.env.NEW_RELIC_LOG || (isDevelopment ? 'stdout' : 'newrelic_agent.log'),
29+
enabled: true
30+
},
31+
32+
// Allow all data to be sent in high-security environments
33+
allow_all_headers: true,
34+
35+
// Enable distributed tracing
36+
distributed_tracing: {
37+
enabled: true
38+
},
39+
40+
// Application logging forwarding - more verbose in dev
41+
application_logging: {
42+
forwarding: {
43+
enabled: true,
44+
max_samples_stored: isDevelopment ? 10000 : 1000
45+
},
46+
metrics: {
47+
enabled: true
48+
},
49+
local_decorating: {
50+
enabled: isDevelopment // Enable log decoration in development
51+
}
52+
},
53+
54+
// Error collection
55+
error_collector: {
56+
enabled: true,
57+
ignore_status_codes: [404],
58+
capture_events: true,
59+
max_event_samples_stored: isDevelopment ? 100 : 30
60+
},
61+
62+
// Performance monitoring - more detailed in dev
63+
slow_sql: {
64+
enabled: true,
65+
max_samples: isDevelopment ? 20 : 10
66+
},
67+
68+
// Transaction tracer - more aggressive in development
69+
transaction_tracer: {
70+
enabled: true,
71+
transaction_threshold: isDevelopment ? 0.1 : 'apdex_f', // 100ms in dev vs apdex_f in prod
72+
record_sql: 'obfuscated',
73+
explain_threshold: isDevelopment ? 100 : 500, // Lower threshold in dev
74+
max_segments: isDevelopment ? 3000 : 2000
75+
},
76+
77+
// Custom insights events
78+
custom_insights_events: {
79+
enabled: true,
80+
max_samples_stored: isDevelopment ? 30000 : 1000
81+
},
82+
83+
// Feature flags for development debugging
84+
feature_flag: {
85+
serverless_mode: false,
86+
await_support: true,
87+
promise_segments: true,
88+
custom_metrics: true
89+
},
90+
91+
// Environment-specific data collection
92+
high_security: isProduction, // Enable high security mode in production
93+
94+
// Attributes - more permissive in development
95+
attributes: {
96+
enabled: true,
97+
include_enabled: true,
98+
exclude: isProduction ? [
99+
'request.headers.cookie',
100+
'request.headers.authorization',
101+
'request.headers.x-api-key'
102+
] : []
103+
}
104+
};

0 commit comments

Comments
 (0)