class-ai-agent 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/.claude/CLAUDE.md +155 -0
  2. package/.claude/agents/backend.md +395 -0
  3. package/.claude/agents/code-reviewer.md +110 -0
  4. package/.claude/agents/copywriter-seo.md +236 -0
  5. package/.claude/agents/frontend.md +384 -0
  6. package/.claude/agents/project-manager.md +201 -0
  7. package/.claude/agents/qa.md +221 -0
  8. package/.claude/agents/security-auditor.md +143 -0
  9. package/.claude/agents/systems-architect.md +211 -0
  10. package/.claude/agents/test-engineer.md +123 -0
  11. package/.claude/agents/ui-ux-designer.md +210 -0
  12. package/.claude/commands/build.md +132 -0
  13. package/.claude/commands/debug.md +242 -0
  14. package/.claude/commands/deploy.md +40 -0
  15. package/.claude/commands/fix-issue.md +42 -0
  16. package/.claude/commands/plan.md +125 -0
  17. package/.claude/commands/review.md +50 -0
  18. package/.claude/commands/simplify.md +222 -0
  19. package/.claude/commands/spec.md +95 -0
  20. package/.claude/commands/test.md +214 -0
  21. package/.claude/references/accessibility-checklist.md +174 -0
  22. package/.claude/references/performance-checklist.md +150 -0
  23. package/.claude/references/security-checklist.md +94 -0
  24. package/.claude/references/testing-patterns.md +183 -0
  25. package/.claude/rules/api-conventions.md +79 -0
  26. package/.claude/rules/clean-code.md +205 -0
  27. package/.claude/rules/code-style.md +86 -0
  28. package/.claude/rules/database.md +60 -0
  29. package/.claude/rules/error-handling.md +92 -0
  30. package/.claude/rules/git-workflow.md +77 -0
  31. package/.claude/rules/monitoring.md +311 -0
  32. package/.claude/rules/naming-conventions.md +260 -0
  33. package/.claude/rules/project-structure.md +65 -0
  34. package/.claude/rules/security.md +90 -0
  35. package/.claude/rules/system-design.md +162 -0
  36. package/.claude/rules/tech-stack.md +456 -0
  37. package/.claude/rules/testing.md +104 -0
  38. package/.claude/settings.json +14 -0
  39. package/.claude/skills/code-review/SKILL.md +208 -0
  40. package/.claude/skills/deploy/SKILL.md +68 -0
  41. package/.claude/skills/deploy/deploy.md +735 -0
  42. package/.claude/skills/incremental-implementation/SKILL.md +210 -0
  43. package/.claude/skills/security-review/SKILL.md +71 -0
  44. package/.claude/skills/tdd/SKILL.md +217 -0
  45. package/.cursor/CURSOR.md +112 -0
  46. package/.cursor/agents/backend.md +395 -0
  47. package/.cursor/agents/code-reviewer.md +110 -0
  48. package/.cursor/agents/copywriter-seo.md +236 -0
  49. package/.cursor/agents/frontend.md +384 -0
  50. package/.cursor/agents/project-manager.md +201 -0
  51. package/.cursor/agents/qa.md +221 -0
  52. package/.cursor/agents/security-auditor.md +143 -0
  53. package/.cursor/agents/systems-architect.md +211 -0
  54. package/.cursor/agents/test-engineer.md +123 -0
  55. package/.cursor/agents/ui-ux-designer.md +210 -0
  56. package/.cursor/commands/build.md +132 -0
  57. package/.cursor/commands/debug.md +242 -0
  58. package/.cursor/commands/deploy.md +40 -0
  59. package/.cursor/commands/fix-issue.md +42 -0
  60. package/.cursor/commands/plan.md +125 -0
  61. package/.cursor/commands/review.md +50 -0
  62. package/.cursor/commands/simplify.md +222 -0
  63. package/.cursor/commands/spec.md +95 -0
  64. package/.cursor/commands/test.md +214 -0
  65. package/.cursor/references/accessibility-checklist.md +174 -0
  66. package/.cursor/references/performance-checklist.md +150 -0
  67. package/.cursor/references/security-checklist.md +94 -0
  68. package/.cursor/references/testing-patterns.md +183 -0
  69. package/.cursor/rules/api-conventions.mdc +85 -0
  70. package/.cursor/rules/clean-code.mdc +211 -0
  71. package/.cursor/rules/code-style.mdc +92 -0
  72. package/.cursor/rules/cursor-overview.mdc +35 -0
  73. package/.cursor/rules/database.mdc +66 -0
  74. package/.cursor/rules/error-handling.mdc +98 -0
  75. package/.cursor/rules/git-workflow.mdc +83 -0
  76. package/.cursor/rules/monitoring.mdc +317 -0
  77. package/.cursor/rules/naming-conventions.mdc +266 -0
  78. package/.cursor/rules/project-structure.mdc +71 -0
  79. package/.cursor/rules/security.mdc +95 -0
  80. package/.cursor/rules/system-design.mdc +168 -0
  81. package/.cursor/rules/tech-stack.mdc +462 -0
  82. package/.cursor/rules/testing.mdc +110 -0
  83. package/.cursor/settings.json +8 -0
  84. package/.cursor/skills/code-review/SKILL.md +208 -0
  85. package/.cursor/skills/deploy/SKILL.md +68 -0
  86. package/.cursor/skills/deploy/deploy.md +735 -0
  87. package/.cursor/skills/incremental-implementation/SKILL.md +210 -0
  88. package/.cursor/skills/security-review/SKILL.md +71 -0
  89. package/.cursor/skills/tdd/SKILL.md +217 -0
  90. package/AGENTS.md +11 -0
  91. package/README.md +405 -0
  92. package/bin/class-ai-agent.cjs +176 -0
  93. package/package.json +38 -0
@@ -0,0 +1,260 @@
1
+ # Naming Conventions
2
+
3
+ > Standard naming rules for cache keys, database identifiers, queues, events, environment variables, and more.
4
+
5
+ ## 🔑 Cache Key Naming
6
+
7
+ ### Format
8
+ ```
9
+ {app}:{version}:{entity}:{identifier}:{variant}
10
+ ```
11
+
12
+ ### Rules
13
+ - Use **colons** (`:`) as separators
14
+ - Use **lowercase snake_case** for each segment
15
+ - Always prefix with app/service name to avoid collision
16
+ - Include version for easy cache invalidation
17
+
18
+ ### Examples
19
+ ```
20
+ # User data
21
+ myapp:v1:user:12345
22
+ myapp:v1:user:12345:profile
23
+ myapp:v1:user:12345:permissions
24
+
25
+ # Lists / collections
26
+ myapp:v1:users:active:list
27
+ myapp:v1:products:category:electronics:page:1
28
+
29
+ # Sessions
30
+ myapp:v1:session:abc123xyz
31
+
32
+ # Rate limiting
33
+ myapp:v1:rate_limit:user:12345:api
34
+ myapp:v1:rate_limit:ip:192.168.1.1
35
+
36
+ # Feature flags
37
+ myapp:v1:feature:new_checkout:enabled
38
+
39
+ # Temporary locks (mutex)
40
+ myapp:v1:lock:payment:order:99999
41
+
42
+ # Aggregates / computed
43
+ myapp:v1:dashboard:user:12345:stats:daily
44
+ ```
45
+
46
+ ### TTL Conventions
47
+ | Data Type | Recommended TTL |
48
+ |-----------|----------------|
49
+ | User session | 7 days |
50
+ | Auth tokens | 15 minutes |
51
+ | User profile | 1 hour |
52
+ | Product catalog | 6 hours |
53
+ | Config/settings | 24 hours |
54
+ | Rate limit windows | 15 minutes |
55
+ | Temporary locks | 30 seconds |
56
+
57
+ ---
58
+
59
+ ## 🗄ïļ Database Naming
60
+
61
+ ### Tables
62
+ ```sql
63
+ -- snake_case, plural nouns
64
+ users
65
+ order_items
66
+ product_categories
67
+ user_role_mappings -- junction tables: entity1_entity2_mappings
68
+ ```
69
+
70
+ ### Columns
71
+ ```sql
72
+ -- snake_case
73
+ id -- primary key (always 'id')
74
+ user_id -- foreign key: {referenced_table_singular}_id
75
+ created_at -- timestamps: {event}_at
76
+ updated_at
77
+ deleted_at -- soft delete
78
+ is_active -- booleans: is_, has_, can_
79
+ has_verified_email
80
+ email -- data fields: plain descriptive name
81
+ full_name
82
+ ```
83
+
84
+ ### Indexes
85
+ ```sql
86
+ -- Pattern: idx_{table}_{columns}
87
+ idx_users_email
88
+ idx_orders_user_id_created_at
89
+ idx_products_category_id_is_active
90
+
91
+ -- Unique indexes
92
+ uniq_users_email
93
+ uniq_products_sku
94
+
95
+ -- Full-text search
96
+ fts_products_name_description
97
+ ```
98
+
99
+ ### Foreign Keys
100
+ ```sql
101
+ -- Pattern: fk_{child_table}_{parent_table}
102
+ fk_orders_users
103
+ fk_order_items_orders
104
+ fk_order_items_products
105
+ ```
106
+
107
+ ### Stored Procedures / Functions
108
+ ```sql
109
+ -- snake_case verbs
110
+ get_user_by_email()
111
+ calculate_order_total()
112
+ archive_old_sessions()
113
+ ```
114
+
115
+ ---
116
+
117
+ ## ðŸ“Ļ Message Queue / Event Naming
118
+
119
+ ### Queue Names
120
+ ```
121
+ # Pattern: {app}.{entity}.{action}
122
+ # Use dots as separators for queues
123
+
124
+ myapp.email.send
125
+ myapp.payment.process
126
+ myapp.order.fulfillment
127
+ myapp.notification.push
128
+ myapp.report.generate
129
+ ```
130
+
131
+ ### Event Names (Domain Events)
132
+ ```
133
+ # Pattern: {entity}.{past_tense_verb}
134
+ # Events describe things that HAPPENED
135
+
136
+ user.registered
137
+ user.email_verified
138
+ order.placed
139
+ order.payment_received
140
+ order.fulfilled
141
+ order.cancelled
142
+ payment.failed
143
+ product.stock_depleted
144
+ ```
145
+
146
+ ### Dead Letter Queues (DLQ)
147
+ ```
148
+ myapp.email.send.dlq
149
+ myapp.payment.process.dlq
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 🌍 Environment Variables
155
+
156
+ ### Rules
157
+ - **UPPER_SNAKE_CASE** for all env vars
158
+ - Prefix with app/service name for non-standard vars
159
+ - Be descriptive, avoid abbreviations
160
+
161
+ ### Standard Variables
162
+ ```bash
163
+ # App
164
+ NODE_ENV=production
165
+ PORT=3000
166
+ APP_NAME=myapp
167
+ APP_URL=https://myapp.com
168
+ LOG_LEVEL=info
169
+
170
+ # Database
171
+ DATABASE_URL=postgresql://...
172
+ DB_HOST=localhost
173
+ DB_PORT=5432
174
+ DB_NAME=myapp_production
175
+ DB_USER=myapp_user
176
+ DB_PASSWORD=...
177
+ DB_POOL_MIN=2
178
+ DB_POOL_MAX=10
179
+
180
+ # Cache
181
+ REDIS_URL=redis://localhost:6379
182
+ REDIS_PASSWORD=...
183
+ CACHE_TTL_DEFAULT=3600
184
+
185
+ # Auth
186
+ JWT_SECRET=...
187
+ JWT_EXPIRES_IN=15m
188
+ JWT_REFRESH_SECRET=...
189
+ JWT_REFRESH_EXPIRES_IN=7d
190
+ BCRYPT_ROUNDS=12
191
+
192
+ # External Services
193
+ SMTP_HOST=...
194
+ SMTP_PORT=587
195
+ SMTP_USER=...
196
+ SMTP_PASS=...
197
+ STRIPE_SECRET_KEY=...
198
+ STRIPE_WEBHOOK_SECRET=...
199
+ AWS_ACCESS_KEY_ID=...
200
+ AWS_SECRET_ACCESS_KEY=...
201
+ AWS_REGION=ap-southeast-1
202
+ S3_BUCKET_NAME=...
203
+
204
+ # Monitoring
205
+ SENTRY_DSN=...
206
+ GRAFANA_API_KEY=...
207
+ ```
208
+
209
+ ---
210
+
211
+ ## 📁 File & Folder Naming
212
+
213
+ ```
214
+ # Files: kebab-case
215
+ user-service.js
216
+ auth-middleware.js
217
+ order-repository.js
218
+ send-welcome-email.js # specific action scripts
219
+
220
+ # Folders: kebab-case, plural for collections
221
+ controllers/
222
+ services/
223
+ repositories/
224
+ utils/
225
+ middleware/
226
+ config/
227
+
228
+ # Test files: match source file + .test
229
+ user-service.test.js
230
+ auth-middleware.test.js
231
+
232
+ # Config files
233
+ .env.development
234
+ .env.production
235
+ docker-compose.dev.yml
236
+ docker-compose.prod.yml
237
+ ```
238
+
239
+ ---
240
+
241
+ ## 🌐 URL / Route Naming
242
+
243
+ ```
244
+ # REST: plural nouns, kebab-case, versioned
245
+ GET /api/v1/users
246
+ GET /api/v1/users/:id
247
+ POST /api/v1/users
248
+ PATCH /api/v1/users/:id
249
+ DELETE /api/v1/users/:id
250
+
251
+ # Nested resources
252
+ GET /api/v1/users/:id/orders
253
+ POST /api/v1/users/:id/orders
254
+
255
+ # Actions that don't fit CRUD (use verbs sparingly)
256
+ POST /api/v1/auth/login
257
+ POST /api/v1/auth/logout
258
+ POST /api/v1/auth/refresh
259
+ POST /api/v1/payments/:id/refund
260
+ ```
@@ -0,0 +1,65 @@
1
+ # Project Structure
2
+
3
+ ## Standard Folder Layout
4
+
5
+ ```
6
+ project-root/
7
+ ├── .claude/ # AI Agent configuration
8
+ │ ├── agents/ # Sub-agent definitions
9
+ │ ├── commands/ # Reusable command workflows
10
+ │ ├── rules/ # Mandatory rules for AI
11
+ │ ├── skills/ # Specialized AI skills
12
+ │ ├── settings.json # Project-level settings
13
+ │ ├── settings.local.json # Local settings (gitignored)
14
+ │ ├── CLAUDE.md # Main AI instructions
15
+ │ └── CLAUDE.local.md # Local AI overrides (gitignored)
16
+ │
17
+ ├── src/ # Application source code
18
+ │ ├── config/ # Configuration files
19
+ │ ├── controllers/ # Route handlers (thin layer)
20
+ │ ├── middleware/ # Express middleware
21
+ │ ├── models/ # Database models/schemas
22
+ │ ├── repositories/ # Data access layer
23
+ │ ├── routes/ # Route definitions
24
+ │ ├── services/ # Business logic layer
25
+ │ ├── utils/ # Utility functions
26
+ │ └── index.js # Application entry point
27
+ │
28
+ ├── tests/ # Test files
29
+ │ ├── unit/ # Unit tests
30
+ │ ├── integration/ # Integration tests
31
+ │ └── e2e/ # End-to-end tests
32
+ │
33
+ ├── docs/ # Documentation
34
+ │ ├── api/ # API documentation
35
+ │ └── architecture/ # Architecture diagrams
36
+ │
37
+ ├── scripts/ # Build and utility scripts
38
+ ├── .env.example # Example environment variables
39
+ ├── .gitignore # Git ignore rules
40
+ ├── package.json
41
+ ├── README.md
42
+ └── CLAUDE.md # Root-level AI instructions (optional)
43
+ ```
44
+
45
+ ## Layered Architecture
46
+ ```
47
+ Request → Routes → Middleware → Controllers → Services → Repositories → Database
48
+ ```
49
+
50
+ - **Routes**: URL mapping only, no logic
51
+ - **Controllers**: Request/response handling, input validation
52
+ - **Services**: Business logic, orchestration
53
+ - **Repositories**: Data access, queries
54
+ - **Models**: Data schemas and types
55
+
56
+ ## File Naming
57
+ - Source files: `kebab-case.js` (`user-service.js`)
58
+ - Test files: `[name].test.js` (`user-service.test.js`)
59
+ - Config files: `kebab-case.js` or `kebab-case.json`
60
+
61
+ ## Environment Files
62
+ - `.env` — Local development (gitignored)
63
+ - `.env.example` — Template committed to git
64
+ - `.env.test` — Test environment (gitignored)
65
+ - `.env.production` — Set in CI/CD, never committed
@@ -0,0 +1,90 @@
1
+ # Security Rules
2
+
3
+ ## ðŸšĻ CRITICAL — Never Violate These
4
+
5
+ - **Never** hardcode secrets, API keys, passwords, or tokens in source code
6
+ - **Never** commit `.env` files to version control
7
+ - **Never** log sensitive data (passwords, tokens, PII)
8
+ - **Never** use `eval()` or `Function()` with user input
9
+ - **Always** validate and sanitize all user inputs
10
+
11
+ ## Environment Variables
12
+ ```js
13
+ // ✅ Always use environment variables for secrets
14
+ const dbPassword = process.env.DB_PASSWORD;
15
+ const jwtSecret = process.env.JWT_SECRET;
16
+
17
+ // ❌ Never hardcode secrets
18
+ const dbPassword = 'mypassword123';
19
+ ```
20
+
21
+ ## Input Validation
22
+ ```js
23
+ // ✅ Validate all incoming data with a schema
24
+ import { z } from 'zod';
25
+
26
+ const loginSchema = z.object({
27
+ email: z.string().email().max(255),
28
+ password: z.string().min(8).max(128)
29
+ });
30
+
31
+ // Sanitize HTML to prevent XSS
32
+ import DOMPurify from 'dompurify';
33
+ const cleanContent = DOMPurify.sanitize(userInput);
34
+ ```
35
+
36
+ ## Authentication
37
+ - Use **JWT** with short expiry (15 min access token, 7 day refresh token)
38
+ - Hash passwords with **bcrypt** (rounds: 12+)
39
+ - Implement rate limiting on auth endpoints
40
+ ```js
41
+ import bcrypt from 'bcrypt';
42
+ const SALT_ROUNDS = 12;
43
+ const hashed = await bcrypt.hash(password, SALT_ROUNDS);
44
+ ```
45
+
46
+ ## Authorization
47
+ ```js
48
+ // ✅ Check permissions on every protected route
49
+ router.delete('/posts/:id', authenticate, authorize('admin'), asyncHandler(deletePost));
50
+
51
+ // ✅ Verify resource ownership
52
+ if (post.authorId !== req.user.id && req.user.role !== 'admin') {
53
+ throw new AppError('Forbidden', 403);
54
+ }
55
+ ```
56
+
57
+ ## HTTP Security Headers
58
+ ```js
59
+ // Use Helmet.js
60
+ import helmet from 'helmet';
61
+ app.use(helmet());
62
+
63
+ // Configure CORS strictly
64
+ app.use(cors({
65
+ origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
66
+ credentials: true
67
+ }));
68
+ ```
69
+
70
+ ## Rate Limiting
71
+ ```js
72
+ import rateLimit from 'express-rate-limit';
73
+
74
+ const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
75
+ const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 5 });
76
+
77
+ app.use('/api/', apiLimiter);
78
+ app.use('/api/auth/', authLimiter);
79
+ ```
80
+
81
+ ## SQL Injection Prevention
82
+ - Always use ORM parameterized queries
83
+ - Never concatenate user input into SQL strings
84
+
85
+ ## Dependency Security
86
+ ```bash
87
+ # Regularly audit dependencies
88
+ npm audit
89
+ npm audit fix
90
+ ```
@@ -0,0 +1,162 @@
1
+ # System Design Rules
2
+
3
+ > Principles from "System Design Interview" (Alex Xu), "Designing Data-Intensive Applications" (Martin Kleppmann), and industry best practices.
4
+
5
+ ## 🏗ïļ Core Principles
6
+
7
+ ### CAP Theorem
8
+ - A distributed system can only guarantee 2 of 3: **Consistency**, **Availability**, **Partition Tolerance**
9
+ - **CP systems** (sacrifice availability): MySQL, ZooKeeper, HBase → use when data correctness is critical
10
+ - **AP systems** (sacrifice consistency): Cassandra, DynamoDB, CouchDB → use for high availability
11
+
12
+ ### Design for Failure
13
+ - Every external call CAN fail — design for it
14
+ - Use **circuit breakers** to prevent cascade failures
15
+ - Use **bulkhead pattern** to isolate failures
16
+ - Implement **graceful degradation** (serve cached/partial data when dependencies fail)
17
+
18
+ ---
19
+
20
+ ## 📐 Scalability Patterns
21
+
22
+ ### Horizontal vs Vertical Scaling
23
+ ```
24
+ Vertical → More CPU/RAM on one machine (limited ceiling)
25
+ Horizontal → More machines (preferred for production)
26
+ ```
27
+
28
+ ### Load Balancing
29
+ - **Round Robin** — equal distribution
30
+ - **Least Connections** — route to least busy server
31
+ - **Consistent Hashing** — for cache/session affinity (minimize remapping on scale)
32
+
33
+ ### Caching Strategies
34
+ | Strategy | Use Case |
35
+ |----------|----------|
36
+ | **Cache-Aside** (Lazy Loading) | Read-heavy, content changes frequently |
37
+ | **Write-Through** | Write-heavy, data must be consistent |
38
+ | **Write-Behind** (Write-Back) | High write throughput, some lag acceptable |
39
+ | **Read-Through** | Cache is always up to date |
40
+
41
+ ### Database Scaling
42
+ - **Read Replicas** — scale read-heavy workloads
43
+ - **Sharding** — partition data horizontally by shard key
44
+ - **Vertical Partitioning** — split tables by column groups
45
+ - **CQRS** — separate read model and write model
46
+
47
+ ---
48
+
49
+ ## 🔄 Async Patterns
50
+
51
+ ### Message Queues
52
+ Use queues (Redis, RabbitMQ, Kafka) when:
53
+ - Processing can be deferred
54
+ - Tasks are slow/expensive (email, PDF gen, notifications)
55
+ - You need to decouple producers from consumers
56
+
57
+ ```
58
+ Producer → [Queue] → Consumer(s)
59
+ ```
60
+
61
+ ### Event-Driven Architecture
62
+ ```js
63
+ // Publish domain events instead of direct service calls
64
+ eventBus.publish('order.created', { orderId, userId, total });
65
+ // Other services subscribe independently
66
+ ```
67
+
68
+ ### Saga Pattern (Distributed Transactions)
69
+ - **Choreography** — each service reacts to events (no central coordinator)
70
+ - **Orchestration** — a saga orchestrator tells each service what to do
71
+
72
+ ---
73
+
74
+ ## 🗄ïļ Database Design
75
+
76
+ ### Normalization vs Denormalization
77
+ - **Normalize** (OLTP) — avoid data duplication, use JOINs
78
+ - **Denormalize** (OLAP/Read-heavy) — duplicate data to eliminate JOINs
79
+
80
+ ### Indexing Rules
81
+ ```sql
82
+ -- ✅ Index columns used in WHERE, JOIN, ORDER BY
83
+ CREATE INDEX idx_users_email ON users(email);
84
+
85
+ -- ❌ Don't index every column — indexes slow down writes
86
+ ```
87
+
88
+ ### N+1 Query Prevention
89
+ ```js
90
+ // ❌ N+1: one query per user
91
+ const users = await db.users.findAll();
92
+ for (const user of users) {
93
+ user.orders = await db.orders.findAll({ where: { userId: user.id } });
94
+ }
95
+
96
+ // ✅ Single query with JOIN or include
97
+ const users = await db.users.findAll({ include: [{ model: db.orders }] });
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 🌐 API Design Patterns
103
+
104
+ ### Rate Limiting Algorithms
105
+ | Algorithm | Best For |
106
+ |-----------|----------|
107
+ | **Token Bucket** | Burst traffic allowed (API gateways) |
108
+ | **Leaky Bucket** | Smooth/constant output rate |
109
+ | **Fixed Window** | Simple, but spiky at window boundaries |
110
+ | **Sliding Window** | Most accurate, higher memory cost |
111
+
112
+ ### Idempotency
113
+ - GET, PUT, DELETE must be idempotent
114
+ - POST operations: use **idempotency keys** for payment/critical actions
115
+ ```
116
+ POST /api/payments
117
+ Idempotency-Key: <uuid>
118
+ ```
119
+
120
+ ### Pagination Patterns
121
+ ```
122
+ Offset: ?page=2&limit=20 → Simple but slow on large offsets
123
+ Cursor: ?cursor=<encoded>&limit=20 → ✅ Preferred for large datasets
124
+ ```
125
+
126
+ ---
127
+
128
+ ## 🔒 Reliability
129
+
130
+ ### Circuit Breaker States
131
+ ```
132
+ CLOSED → OPEN (after N failures) → HALF-OPEN (probe) → CLOSED
133
+ ```
134
+
135
+ ### Retry Strategy
136
+ ```js
137
+ // ✅ Exponential backoff with jitter
138
+ const delay = Math.min(baseDelay * 2 ** attempt + Math.random() * 1000, maxDelay);
139
+ ```
140
+
141
+ ### Health Checks
142
+ ```
143
+ GET /health → Basic liveness (is the service running?)
144
+ GET /health/ready → Readiness (is the service ready to serve traffic?)
145
+ GET /health/live → Liveness (should Kubernetes restart this pod?)
146
+ ```
147
+
148
+ ---
149
+
150
+ ## 📊 Back-of-Envelope Estimation
151
+
152
+ | Resource | Approximate Speed |
153
+ |----------|------------------|
154
+ | L1 cache reference | 0.5 ns |
155
+ | L2 cache reference | 7 ns |
156
+ | RAM access | 100 ns |
157
+ | SSD random read | 150 Ξs |
158
+ | Network round trip (same DC) | 0.5 ms |
159
+ | HDD seek | 10 ms |
160
+ | Network round trip (cross continent) | 150 ms |
161
+
162
+ > Rule of thumb: Prefer Redis (in-memory) over DB for anything needing < 1ms latency