-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path.cursorrules
More file actions
393 lines (353 loc) · 15.6 KB
/
.cursorrules
File metadata and controls
393 lines (353 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
{
"name": "hexfeed-java-assistant",
"version": "1.0.0",
"description": "MCP configuration for building Hexagon Feed System with Spring Boot",
"context": {
"project": {
"name": "Hexagon Feed System",
"type": "Spring Boot Java Backend",
"description": "Location-based social feed using hexagonal spatial indexing (H3)",
"architecture": "Microservices with WebSocket real-time updates"
},
"tech_stack": {
"language": "Java 17",
"framework": "Spring Boot 3.2.x",
"build_tool": "Maven",
"databases": {
"relational": "PostgreSQL 15",
"nosql": "Cassandra 4.x (or PostgreSQL initially)",
"cache": "Redis 7.x"
},
"messaging": "Apache Kafka / RabbitMQ",
"real_time": "WebSocket with STOMP",
"spatial": "Uber H3 Library (hexagonal spatial indexing)",
"monitoring": "Prometheus + Grafana + Loki",
"testing": "JUnit 5, Mockito, TestContainers"
},
"key_concepts": {
"hexagonal_indexing": "H3 - Uber's Hierarchical Hexagonal Spatial Index at resolution 7-8",
"feed_algorithm": "K-way merge of 7 hexagons (center + 6 neighbors) sorted by timestamp DESC",
"pagination": "Cursor-based using timestamp+post_id composite key",
"rate_limiting": "Token bucket algorithm with Redis",
"real_time": "Kafka → WebSocket broadcast to subscribed users per hexagon",
"caching": "Multi-layer: Redis for feed pages, 80%+ hit rate target"
}
},
"design_references": {
"hld_key_points": [
"1M concurrent users target",
"Real-time WebSocket updates",
"7 hexagons queried per feed request (parallel)",
"Reverse chronological order",
"Horizontal scalability via hex_id partitioning"
],
"lld_key_points": [
"Database: Posts partitioned by hex_id, sorted by timestamp DESC",
"K-way merge algorithm: O(N log K) using PriorityQueue",
"Rate limiting: 10 posts/minute using Redis atomic operations",
"Cache invalidation: Write-through + TTL-based (300s)",
"WebSocket: Pub/Sub per hexagon with heartbeat every 30s"
]
},
"project_structure": {
"packages": {
"controller": "REST endpoints and WebSocket controllers",
"service": "Business logic (LocationService, FeedAggregationService, etc.)",
"repository": "Data access layer (JPA repositories)",
"model.entity": "JPA entities (User, Post, UserSession)",
"model.dto": "Request/Response DTOs",
"config": "Configuration classes (Redis, Kafka, WebSocket, Security)",
"util": "Utilities (H3Util, ValidationUtil, PaginationUtil)",
"exception": "Custom exceptions and global handler",
"messaging": "Kafka producers and consumers",
"websocket": "WebSocket connection management",
"security": "JWT utilities and filters"
}
},
"coding_standards": {
"naming_conventions": {
"classes": "PascalCase (e.g., FeedAggregationService)",
"methods": "camelCase (e.g., getHexIdForLocation)",
"constants": "UPPER_SNAKE_CASE (e.g., MAX_CONTENT_LENGTH)",
"packages": "lowercase (e.g., com.hexfeed.service)"
},
"best_practices": [
"Use Lombok to reduce boilerplate (@Data, @Builder, @Slf4j)",
"Always validate inputs using @Valid and custom validators",
"Use @Transactional for database operations",
"Use @Async for non-blocking operations (cache invalidation, Kafka)",
"Use CompletableFuture for parallel database queries",
"Inject dependencies via constructor (not @Autowired field)",
"Use Optional<> for nullable returns",
"Always handle exceptions with try-catch and proper logging",
"Use meaningful variable names (avoid single letters except loops)",
"Add JavaDoc for public methods in service layer"
],
"error_handling": {
"strategy": "Global exception handler with @RestControllerAdvice",
"custom_exceptions": [
"ValidationException (400)",
"RateLimitException (429)",
"ResourceNotFoundException (404)",
"UnauthorizedException (401)"
],
"response_format": "ApiResponse<T> { boolean success, T data, ErrorInfo error }"
}
},
"implementation_priorities": {
"phase_1": "Database schema + JPA entities + basic repositories",
"phase_2": "Location Service (H3 integration) + caching",
"phase_3": "Feed Aggregation (K-way merge algorithm)",
"phase_4": "Post Creation + Rate Limiting + Kafka producer",
"phase_5": "WebSocket + Kafka consumer for real-time updates",
"phase_6": "Security (JWT) + REST controllers",
"phase_7": "Testing + Optimization + Deployment"
},
"critical_algorithms": {
"k_way_merge": {
"purpose": "Merge 7 sorted lists (hex feeds) into single sorted feed",
"data_structure": "PriorityQueue<PostIterator>",
"comparator": "Compare by timestamp DESC (negate for max-heap behavior)",
"time_complexity": "O(N log K) where N=limit, K=7",
"space_complexity": "O(K) = O(7)",
"implementation_notes": [
"Initialize heap with first post from each hex",
"Poll min (actually max due to negation), add to result",
"Push next post from same hex if available",
"Stop when result reaches limit"
]
},
"rate_limiting": {
"algorithm": "Token Bucket",
"storage": "Redis with atomic Lua script",
"capacity": "10 tokens",
"refill_rate": "10 tokens per minute",
"implementation_notes": [
"Key: rate_limit:{userId}",
"Value: {tokens: int, lastRefill: timestamp}",
"Atomic get-calculate-set using Redis EVAL",
"Return retry_after seconds on limit exceeded"
]
},
"cursor_pagination": {
"format": "base64(timestamp|post_id)",
"query_logic": "WHERE (timestamp < cursor_ts OR (timestamp = cursor_ts AND post_id < cursor_id))",
"benefits": [
"Consistent results with concurrent inserts",
"O(1) complexity vs O(n) for offset",
"No duplicates or skipped records"
]
}
},
"database_design": {
"posts_table": {
"partition_key": "hex_id",
"sort_keys": "timestamp DESC, post_id",
"indexes": [
"PRIMARY KEY ((hex_id), timestamp, post_id)",
"INDEX idx_user_posts ON (user_id, timestamp)",
"INDEX idx_post_lookup ON (post_id)"
],
"important_notes": [
"For MVP: Use PostgreSQL with table partitioning by hex_id",
"For scale: Migrate to Cassandra with same schema",
"Always query with hex_id in WHERE clause for performance"
]
},
"caching_strategy": {
"keys": {
"feed": "feed:{hex_id}:{page}",
"session": "session:{user_id}",
"hex_neighbors": "hex_neighbors:{hex_id}",
"post": "post:{post_id}"
},
"ttl": {
"feed": "300 seconds (5 min)",
"session": "3600 seconds (1 hour)",
"hex_neighbors": "86400 seconds (24 hours)",
"post": "600 seconds (10 min)"
},
"invalidation": [
"On new post: DELETE feed:{hex_id}:1",
"On post delete: DELETE feed:{hex_id}:* and post:{post_id}"
]
}
},
"api_design": {
"endpoints": {
"GET /api/v1/feed": {
"params": "latitude, longitude, page, limit",
"auth": "required (JWT)",
"returns": "FeedResponse with posts sorted by timestamp DESC",
"notes": "Queries 7 hexagons in parallel, merges results"
},
"POST /api/v1/posts": {
"body": "PostRequest {content, latitude, longitude, metadata}",
"auth": "required",
"returns": "PostResponse",
"notes": "Rate limited to 10 posts/min, publishes to Kafka"
},
"DELETE /api/v1/posts/{postId}": {
"auth": "required (must own post)",
"returns": "Success message",
"notes": "Soft delete, invalidates cache"
}
},
"websocket": {
"endpoint": "/ws",
"protocol": "STOMP over SockJS",
"messages": {
"subscribe": "/app/subscribe (client sends lat/lon)",
"subscribe_ack": "/user/queue/feed (server confirms)",
"new_post": "/user/queue/feed (server pushes)",
"ping": "/user/queue/feed (heartbeat every 30s)",
"pong": "/app/pong (client responds)"
}
}
},
"testing_guidance": {
"unit_tests": {
"focus": "Service layer logic, utilities, algorithms",
"mocking": "Mock repositories, external services",
"coverage_target": "80%+",
"examples": [
"Test K-way merge with various input sizes",
"Test rate limiter with edge cases",
"Test H3 hex conversion",
"Test pagination cursor encoding/decoding"
]
},
"integration_tests": {
"focus": "Complete flows, API endpoints",
"tools": "@SpringBootTest, TestRestTemplate, TestContainers",
"examples": [
"Create post → verify in feed",
"Real-time update flow: REST → Kafka → WebSocket",
"Cache hit/miss scenarios",
"Concurrent user feed requests"
]
},
"performance_tests": {
"tool": "JMeter or Gatling",
"scenarios": [
"100 concurrent users requesting feed",
"50 users creating posts simultaneously",
"WebSocket connection stability"
],
"targets": {
"feed_api": "< 1s (p95)",
"post_creation": "< 500ms (p95)",
"websocket_latency": "< 200ms"
}
}
},
"common_pitfalls": [
{
"issue": "N+1 query problem in feed aggregation",
"solution": "Use @EntityGraph or JOIN FETCH for user data"
},
{
"issue": "Race condition in rate limiter",
"solution": "Use Redis Lua script for atomic operations"
},
{
"issue": "Memory issues with large feed merges",
"solution": "Use streaming/lazy evaluation, don't load all posts"
},
{
"issue": "WebSocket connection drops",
"solution": "Implement heartbeat mechanism, auto-reconnect on client"
},
{
"issue": "Cache stampede on popular hexagons",
"solution": "Use Redis SETNX for lock, probabilistic early expiration"
},
{
"issue": "Slow queries on posts table",
"solution": "Ensure composite index on (hex_id, timestamp, post_id)"
}
],
"dependencies": {
"required": [
"spring-boot-starter-web",
"spring-boot-starter-data-jpa",
"spring-boot-starter-data-redis",
"spring-kafka",
"spring-boot-starter-websocket",
"postgresql (driver)",
"com.uber:h3:4.1.1",
"lombok",
"spring-boot-starter-validation",
"io.jsonwebtoken:jjwt:0.9.1"
],
"optional": [
"spring-boot-starter-data-cassandra (for scale)",
"spring-boot-starter-actuator (monitoring)",
"micrometer-registry-prometheus (metrics)",
"spring-boot-starter-security (JWT)"
],
"testing": [
"spring-boot-starter-test",
"testcontainers (PostgreSQL, Redis, Kafka)",
"mockito-core"
]
},
"cursor_prompts": {
"when_creating_entity": "Create a JPA entity following the database schema in LLD. Include Lombok annotations (@Data, @Entity, @Table), proper validation (@NotNull, @Size), and audit fields (@CreatedDate, @LastModifiedDate). Use UUID for primary keys with @GeneratedValue.",
"when_creating_repository": "Create a repository interface extending JpaRepository. Add custom query methods using Spring Data JPA naming conventions. Include methods for: finding by hex_id with pagination, cursor-based pagination queries, and count operations.",
"when_creating_service": "Create a service class with @Service annotation. Inject dependencies via constructor. Implement business logic according to LLD specifications. Use @Transactional for database operations, @Async for non-blocking tasks, and CompletableFuture for parallel queries. Add proper error handling and logging.",
"when_implementing_k_way_merge": "Implement the K-way merge algorithm using PriorityQueue as described in LLD Section 4.1. Use a custom Comparator for timestamp DESC ordering. Create a PostIterator inner class to track position in each hex feed. Ensure O(N log K) complexity.",
"when_implementing_rate_limiter": "Implement token bucket rate limiting using Redis. Create a Lua script for atomic get-calculate-set operations. Key format: 'rate_limit:{userId}'. Store tokens and lastRefill timestamp. Refill at 10 tokens per minute. Return retry_after seconds on limit exceeded.",
"when_creating_controller": "Create a REST controller with @RestController and @RequestMapping. Add @Valid for request validation, @AuthenticationPrincipal for JWT user, and proper HTTP status codes. Return ApiResponse<T> wrapper. Handle exceptions will be caught by global handler.",
"when_implementing_websocket": "Configure WebSocket with @EnableWebSocketMessageBroker. Create STOMP endpoints. Use @MessageMapping for client messages and @SendToUser for responses. Implement subscription management tracking which users are subscribed to which hexagons. Use SimpMessagingTemplate for broadcasting.",
"when_writing_tests": "Create test class with @SpringBootTest or @DataJpaTest. Use @MockBean for dependencies. Write descriptive test method names (test_methodName_scenario_expectedResult). Include happy path and edge cases. Verify using assertions and verify() for mocks.",
"when_optimizing_performance": "Analyze query plans with EXPLAIN. Add database indexes for frequently queried columns. Implement caching with @Cacheable. Use pagination to limit result sets. Profile with Spring Boot Actuator metrics. Optimize connection pool sizes.",
"when_debugging": "Add detailed logging with @Slf4j. Log method entry/exit with parameters. Log cache hits/misses. Log database query times. Use meaningful log levels (DEBUG for verbose, INFO for important, WARN for issues, ERROR for failures)."
},
"quick_reference": {
"h3_usage": {
"convert_to_hex": "H3Core.latLngToCell(lat, lon, resolution)",
"get_neighbors": "H3Core.gridDisk(hexId, k)",
"resolution_7": "~2.5km edge length, good for neighborhoods"
},
"redis_commands": {
"cache_feed": "SET feed:{hex_id}:{page} {json} EX 300",
"get_feed": "GET feed:{hex_id}:{page}",
"invalidate": "DEL feed:{hex_id}:1",
"rate_limit": "EVAL {lua_script} 1 rate_limit:{userId}"
},
"kafka_topics": {
"new_post_events": "Partition by hex_id for ordering",
"consumer_group": "websocket-group with concurrency=3"
}
},
"development_workflow": {
"order_of_implementation": [
"1. Setup project structure and dependencies",
"2. Create database schema and entities",
"3. Implement repositories with tests",
"4. Build Location Service (H3 integration)",
"5. Implement Feed Aggregation (K-way merge)",
"6. Build Post Creation with rate limiting",
"7. Add Kafka producer/consumer",
"8. Implement WebSocket manager",
"9. Create REST controllers with security",
"10. Add comprehensive tests",
"11. Setup monitoring and logging",
"12. Deploy to Oracle Cloud"
],
"git_workflow": [
"Create feature branches from main",
"Commit frequently with clear messages",
"Write tests before pushing",
"Code review before merging",
"Keep commits small and focused"
]
},
"documentation_requirements": {
"code_comments": "Add JavaDoc for all public methods in service layer",
"readme": "Include setup instructions, environment variables, API docs",
"api_docs": "Use Swagger/OpenAPI annotations",
"architecture_diagram": "Reference HLD and LLD documents"
}
}