Refactor service documentation and enhance bilingual support

- Updated service template structure in `ARCHITECTURE.md` and `README.md` for clarity and usability.
- Enhanced bilingual documentation across skills, increasing the number of available skills from 15 to 25.
- Added new sections on event-driven architecture, inter-service communication, and performance optimization.
- Improved formatting and removed outdated references to streamline the documentation experience.
This commit is contained in:
Ho Ngoc Hai
2026-01-01 10:06:27 +07:00
parent 9b6c585f57
commit 478254400a
34 changed files with 8740 additions and 30 deletions

View File

@@ -8,7 +8,7 @@ Cursor Skills are specialized knowledge modules that guide AI assistants in foll
## Available Skills
The GoodGo platform includes **15 Cursor Skills** organized by category:
The GoodGo platform includes **25 Cursor Skills** organized by category:
### API & Data Layer
@@ -46,6 +46,24 @@ Service layer organization and patterns for GoodGo microservices. Use when imple
#### [Kubernetes Deployment](./deployment-kubernetes.md)
Kubernetes deployment patterns for GoodGo microservices. Use when deploying to staging/production, creating K8s manifests, configuring HPA, setting up ingress, or troubleshooting K8s deployments.
#### [Event-Driven Architecture](./event-driven-architecture.md)
Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
#### [Inter-Service Communication](./inter-service-communication.md)
Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
#### [Data Consistency Patterns](./data-consistency-patterns.md)
Data consistency patterns for distributed microservices including Saga patterns, distributed transactions, eventual consistency, compensation, and idempotency. Use when handling distributed transactions, implementing eventual consistency, or managing data synchronization across services.
#### [API Gateway Advanced](./api-gateway-advanced.md)
Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience. Use when implementing API aggregation, service composition, or advanced gateway features.
#### [Configuration Management](./configuration-management.md)
Configuration management patterns for GoodGo microservices including feature flags, dynamic configuration reloading, environment-specific configurations, and secrets management. Use when implementing feature toggles, managing configuration, or handling environment variables.
#### [Performance Optimization](./performance-optimization.md)
Performance optimization patterns for GoodGo microservices including database query optimization, memory leak detection, profiling, connection pooling, and caching strategies. Use when optimizing performance, profiling applications, or detecting performance bottlenecks.
#### [Observability & Monitoring](./observability-monitoring.md)
Observability and monitoring patterns for GoodGo microservices. Use when adding metrics, implementing logging, setting up tracing, creating health checks, or debugging production issues.
@@ -55,6 +73,18 @@ Resilience patterns for GoodGo microservices including circuit breaker, retry st
#### [Microservices Development Process](./microservices-development-process.md)
Standard development process for creating and maintaining microservices in GoodGo platform. Use when creating new services, migrating services, refactoring services, or planning service implementations.
#### [CI/CD Advanced Patterns](./cicd-advanced-patterns.md)
Advanced CI/CD patterns for GoodGo microservices including blue-green deployments, canary releases, automated rollback, deployment verification, and progressive delivery. Use when implementing advanced deployment strategies, automated rollbacks, or progressive delivery pipelines.
#### [Infrastructure as Code](./infrastructure-as-code.md)
Infrastructure as Code patterns for GoodGo platform including Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, and multi-environment management. Use when managing infrastructure, implementing GitOps, or creating reusable infrastructure modules.
#### [API Versioning Strategy](./api-versioning-strategy.md)
API versioning strategies for GoodGo microservices including semantic versioning, backward compatibility patterns, API deprecation, version negotiation, and breaking changes handling. Use when versioning APIs, handling breaking changes, or implementing API deprecation strategies.
#### [Service Discovery & Registry](./service-discovery-registry.md)
Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration. Use when implementing service discovery, managing service health, or integrating with service mesh.
### Standards & Security
#### [Project Rules](./project-rules.md)
@@ -80,6 +110,12 @@ Guidelines for writing technical documentation in the GoodGo project. Use when c
| Write documentation | Documentation, Comment Code |
| Implement authentication | Security, API Design, Database & Prisma |
| Optimize database queries | Database & Prisma, Observability |
| Implement event-driven communication | Event-Driven Architecture, Resilience Patterns |
| Implement service-to-service calls | Inter-Service Communication, Security, Resilience Patterns |
| Handle distributed transactions | Data Consistency Patterns, Event-Driven Architecture |
| Optimize performance | Performance Optimization, Observability & Monitoring |
| Manage feature flags | Configuration Management |
| Deploy with zero downtime | CI/CD Advanced Patterns, Deployment Kubernetes |
### Skill Dependencies
@@ -108,6 +144,39 @@ Application Layer
└── Error Handling Patterns
Infrastructure
├── Event-Driven Architecture
│ ├── Resilience Patterns
│ ├── Error Handling Patterns
│ └── Observability & Monitoring
├── Inter-Service Communication
│ ├── API Design
│ ├── Security
│ └── Resilience Patterns
├── Data Consistency Patterns
│ ├── Event-Driven Architecture
│ ├── Database & Prisma
│ └── Error Handling Patterns
├── API Gateway Advanced
│ ├── Middleware Patterns
│ ├── Security
│ └── API Design
├── Configuration Management
│ └── Observability & Monitoring
├── Performance Optimization
│ ├── Database & Prisma
│ ├── Caching Patterns
│ └── Observability & Monitoring
├── CI/CD Advanced Patterns
│ ├── Deployment Kubernetes
│ └── Testing Patterns
├── Infrastructure as Code
│ └── Deployment Kubernetes
├── API Versioning Strategy
│ ├── API Design
│ └── Middleware Patterns
├── Service Discovery & Registry
│ ├── Deployment Kubernetes
│ └── Observability & Monitoring
└── Resilience Patterns
├── Error Handling Patterns
└── Service Layer Patterns

View File

@@ -0,0 +1,58 @@
---
name: api-gateway-advanced
description: Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience.
---
# API Gateway Advanced Patterns
## When to Use This Skill
Use this skill when:
- Implementing API composition and aggregation
- Transforming requests/responses at gateway level
- Integrating service mesh with Traefik
- Implementing advanced routing strategies
- Adding gateway-level circuit breakers
- Implementing API versioning at gateway
## Key Patterns
### API Composition
```typescript
// Aggregate multiple service responses
const [user, orders, payments] = await Promise.all([
userClient.get(`/users/${userId}`),
orderClient.get(`/orders?userId=${userId}`),
paymentClient.get(`/payments?userId=${userId}`),
]);
```
### Request/Response Transformation
```typescript
// Transform at gateway level
transformer.addRule({
path: '/api/v1/users',
requestTransform: (req) => {
if (!req.query.page) req.query.page = '1';
return req;
},
responseTransform: (res, data) => {
return { success: true, data };
},
});
```
## Best Practices
1. Use API composition for aggregating related data
2. Cache at gateway for frequently accessed data
3. Implement circuit breaker at gateway level
4. Keep transformations simple and testable
## Resources
- [Traefik Documentation](https://doc.traefik.io/traefik/)
- [Middleware Patterns](./middleware-patterns.md)
- Skill Source: `.cursor/skills/api-gateway-advanced/SKILL.md`

View File

@@ -0,0 +1,55 @@
---
name: api-versioning-strategy
description: API versioning strategies for GoodGo microservices including semantic versioning, backward compatibility patterns, API deprecation, version negotiation, and breaking changes handling.
---
# API Versioning Strategy
## When to Use This Skill
Use this skill when:
- Versioning APIs
- Handling breaking changes
- Implementing API deprecation
- Maintaining backward compatibility
- Implementing version negotiation
## Key Patterns
### URL Path Versioning
```typescript
// Version routes
router.use('/v1', v1Router);
router.use('/v2', v2Router);
```
### Header-Based Versioning
```typescript
// Version negotiation
const acceptHeader = req.headers.accept;
const version = acceptHeader.match(/application\/vnd\.goodgo\.v(\d+)\+json/)[1];
```
### Deprecation
```typescript
// Deprecation headers
res.setHeader('Deprecation', 'true');
res.setHeader('Sunset', '2024-12-31');
res.setHeader('Warning', 'API version 1 is deprecated');
```
## Best Practices
1. Choose versioning strategy and be consistent
2. Use semantic versioning (MAJOR.MINOR.PATCH)
3. Always deprecate before removing
4. Provide migration guides
5. Maintain backward compatibility when possible
## Resources
- [API Design](./api-design.md)
- Skill Source: `.cursor/skills/api-versioning-strategy/SKILL.md`

View File

@@ -0,0 +1,61 @@
---
name: cicd-advanced-patterns
description: Advanced CI/CD patterns for GoodGo microservices including blue-green deployments, canary releases, automated rollback, deployment verification, and progressive delivery.
---
# CI/CD Advanced Patterns
## When to Use This Skill
Use this skill when:
- Implementing blue-green deployments
- Setting up canary releases
- Implementing automated rollback mechanisms
- Creating deployment verification pipelines
- Implementing progressive delivery
## Key Patterns
### Blue-Green Deployment
```yaml
# Switch service selector between blue/green
apiVersion: v1
kind: Service
spec:
selector:
version: blue # Switch to green after verification
```
### Canary Deployment
```yaml
# Split traffic between stable and canary
http:
- route:
- destination:
subset: stable
weight: 90
- destination:
subset: canary
weight: 10
```
### Automated Rollback
```bash
# Rollback to previous revision
kubectl rollout undo deployment/service --to-revision=1
```
## Best Practices
1. Use blue-green for zero-downtime deployments
2. Use canary for gradual rollouts with monitoring
3. Always have automated rollback plan
4. Run smoke tests immediately after deployment
## Resources
- [Deployment Kubernetes](./deployment-kubernetes.md)
- Skill Source: `.cursor/skills/cicd-advanced-patterns/SKILL.md`

View File

@@ -0,0 +1,57 @@
---
name: configuration-management
description: Configuration management patterns for GoodGo microservices including feature flags, dynamic configuration reloading, environment-specific configurations, and secrets management.
---
# Configuration Management Patterns
## When to Use This Skill
Use this skill when:
- Implementing feature flags and feature toggles
- Managing environment-specific configurations
- Implementing dynamic configuration reloading
- Managing secrets and sensitive configuration
- Implementing configuration validation
## Key Patterns
### Feature Flags
```typescript
// Check if feature is enabled
const enabled = await featureFlagService.isEnabled('new-feature', userId);
if (enabled) {
// Use new feature
}
```
### Dynamic Configuration
```typescript
// Load and auto-reload configuration
await configService.load();
configService.startAutoReload(60000); // Reload every minute
const value = configService.get('config-key', 'default-value');
```
### Configuration Validation
```typescript
// Validate with Zod
const config = validateConfig(process.env);
```
## Best Practices
1. Always validate configuration at startup
2. Provide sensible defaults
3. Never commit secrets to code
4. Use feature flags for gradual rollouts
## Resources
- [Feature Flags Pattern](https://martinfowler.com/articles/feature-toggles.html)
- Skill Source: `.cursor/skills/configuration-management/SKILL.md`

View File

@@ -0,0 +1,96 @@
---
name: data-consistency-patterns
description: Data consistency patterns for distributed microservices including Saga patterns, distributed transactions, eventual consistency, compensation, and idempotency. Use when handling distributed transactions, implementing eventual consistency, or managing data synchronization across services.
---
# Data Consistency Patterns
## When to Use This Skill
Use this skill when:
- Implementing distributed transactions across multiple services
- Handling eventual consistency in microservices
- Implementing Saga patterns for distributed workflows
- Designing compensation strategies for failed transactions
- Implementing idempotent operations
- Managing data synchronization across services
- Handling conflict resolution
## Core Concepts
### ACID vs BASE
**ACID (Traditional):** Atomicity, Consistency, Isolation, Durability
**BASE (Distributed):** Basic Availability, Soft state, Eventual consistency
### Consistency Models
- **Strong Consistency**: All nodes see same data at same time
- **Eventual Consistency**: System becomes consistent over time
- **Weak Consistency**: No guarantees about when consistency occurs
## Key Patterns
### Saga Orchestrator Pattern
```typescript
// Centralized orchestrator coordinates steps
const saga = new SagaOrchestrator();
await saga.execute({
sagaId: 'saga_123',
steps: [
{ name: 'create-order', execute: createOrder, compensate: cancelOrder },
{ name: 'reserve-inventory', execute: reserveInventory, compensate: releaseInventory },
{ name: 'process-payment', execute: chargePayment, compensate: refundPayment },
],
data: {},
status: 'pending',
});
```
### Saga Choreography Pattern
```typescript
// Services react to events
eventConsumer.on('order.created', async (event) => {
await inventoryService.reserve(event.data.items);
await eventPublisher.publish('inventory.reserved', {...});
});
```
### Idempotency
```typescript
// Execute operation with idempotency check
await idempotencyHandler.execute(
idempotencyKey,
async () => await userService.create(data)
);
```
### Optimistic Locking
```typescript
// Update with version check
await optimisticLockService.updateWithLock(
repository,
id,
(current) => ({ ...current, name: newName })
);
```
## Best Practices
1. **Design Compensations**: Every step needs compensation
2. **Idempotent Steps**: Make steps idempotent for retries
3. **Conflict Resolution**: Define resolution strategies
4. **Monitoring**: Track saga execution and consistency lag
5. **Read Models**: Use separate read models for queries (CQRS)
## Resources
- [Saga Pattern](https://microservices.io/patterns/data/saga.html)
- [Event-Driven Architecture](./event-driven-architecture.md)
- [Error Handling Patterns](./error-handling-patterns.md)
- Skill Source: `.cursor/skills/data-consistency-patterns/SKILL.md`

View File

@@ -0,0 +1,332 @@
---
name: event-driven-architecture
description: Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
---
# Event-Driven Architecture Patterns
## When to Use This Skill
Use this skill when:
- Implementing asynchronous communication between services
- Decoupling services for better scalability
- Publishing domain events for downstream consumers
- Consuming events from other services
- Implementing event sourcing patterns
- Implementing CQRS (Command Query Responsibility Segregation)
- Exposing event streams via HTTP (SSE/WebSocket)
- Handling eventual consistency across services
- Building reactive systems that respond to changes
- Integrating with Apache Kafka message broker
## Core Concepts
### Event-Driven vs Request-Response
**Request-Response (Synchronous):**
- Client waits for response
- Tight coupling between services
- Blocking operations
- Immediate consistency
- Use Traefik API Gateway for HTTP/REST
**Event-Driven (Asynchronous):**
- Fire-and-forget publishing
- Loose coupling between services
- Non-blocking operations
- Eventual consistency
- Use Kafka for message broker
### Kafka Fundamentals
- **Topics**: Named streams of events (e.g., `user.created`, `order.placed`)
- **Partitions**: Physical division of topics for parallelism and scaling
- **Consumer Groups**: Groups of consumers that work together to process events
- **Producers**: Services that publish events to topics
- **Consumers**: Services that subscribe to topics and process events
### Traefik Integration
Traefik serves dual purpose:
- **API Gateway**: Routes synchronous HTTP/REST requests
- **Event Streaming Gateway**: Routes SSE/WebSocket connections to event streaming endpoints
Services publish events to Kafka, then expose SSE/WebSocket endpoints that consume from Kafka for HTTP clients.
## Key Patterns
### Event Publishing
```typescript
// src/core/events/event-publisher.ts
import { producer } from '../config/kafka.config';
import { logger } from '@goodgo/logger';
import { v4 as uuidv4 } from 'uuid';
export class EventPublisher {
async publish<T extends BaseEvent>(
topic: string,
event: Omit<T, 'eventId' | 'timestamp' | 'source'>,
options?: { partitionKey?: string }
): Promise<void> {
const fullEvent: T = {
...event,
eventId: uuidv4(),
timestamp: new Date().toISOString(),
source: this.serviceName,
} as T;
await producer.send({
topic,
messages: [{
key: options?.partitionKey || fullEvent.eventId,
value: JSON.stringify(fullEvent),
headers: {
'event-type': event.eventType,
'event-version': event.eventVersion,
},
}],
});
}
}
```
### Event Consuming
```typescript
// src/core/events/event-consumer.ts
import { kafka } from '../config/kafka.config';
export class EventConsumer {
private handlers: Map<string, EventHandler[]> = new Map();
on<T extends BaseEvent>(eventType: string, handler: EventHandler<T>): void {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, []);
}
this.handlers.get(eventType)!.push(handler);
}
async start(topics: string[]): Promise<void> {
await this.consumer.connect();
await this.consumer.subscribe({ topics, fromBeginning: false });
await this.consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const event: BaseEvent = JSON.parse(message.value?.toString() || '{}');
const handlers = this.handlers.get(event.eventType) || [];
await Promise.all(handlers.map(h => h.handle(event)));
},
});
}
}
```
### Outbox Pattern for Transactional Publishing
```typescript
// Store event in database within transaction
await prisma.outboxEvent.create({
data: {
eventType: 'user.created',
eventData: userData,
topic: 'user.created',
status: 'PENDING',
},
});
// Separate process publishes from outbox to Kafka
async function processOutbox() {
const events = await prisma.outboxEvent.findMany({
where: { status: 'PENDING' },
});
for (const event of events) {
await eventPublisher.publish(event.topic, event.eventData);
await prisma.outboxEvent.update({
where: { id: event.id },
data: { status: 'PUBLISHED' },
});
}
}
```
### SSE Endpoint for Event Streaming
```typescript
// src/modules/events/events.controller.ts
async streamEvents(req: Request, res: Response): Promise<void> {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const topic = req.query.topic as string;
const consumer = kafka.consumer({ groupId: `sse-${Date.now()}` });
await consumer.connect();
await consumer.subscribe({ topic, fromBeginning: false });
await consumer.run({
eachMessage: async ({ message }) => {
const event = JSON.parse(message.value?.toString() || '{}');
res.write(`data: ${JSON.stringify(event)}\n\n`);
},
});
req.on('close', async () => {
await consumer.disconnect();
});
}
```
## Event Structure
```typescript
interface BaseEvent {
eventId: string;
eventType: string;
eventVersion: string;
timestamp: string;
source: string;
correlationId?: string;
traceId?: string;
data: unknown;
}
```
## Best Practices
### Event Naming Conventions
- **Event Type**: `{domain}.{action}.v{version}` (e.g., `user.created.v1`)
- **Topic**: `{domain}.{entity}.{action}` (e.g., `user.created`)
- Use lowercase with dots as separators
- Keep names descriptive and consistent
### Partition Key Selection
- Use entity ID for ordering guarantees (same entity → same partition)
- Use correlation ID for request tracing
- Use user ID for user-scoped events
- Avoid high-cardinality keys (distributes evenly)
### Event Ordering Guarantees
- Kafka guarantees ordering **per partition**
- Use partition key to ensure related events go to same partition
- Events in different partitions have no ordering guarantee
- Don't rely on global ordering across all events
### Error Handling
- Implement Dead Letter Queue (DLQ) for failed events
- Use retry with exponential backoff
- Log all event processing failures
- Monitor consumer lag and DLQ size
### Observability
- Log all published and consumed events
- Track metrics: events published/consumed, processing duration, consumer lag
- Add distributed tracing to event flows
- Include correlation IDs for request tracking
## Infrastructure Setup
### Docker Compose (Local)
```yaml
services:
kafka:
image: confluentinc/cp-kafka:7.4.0
ports:
- "9092:9092"
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
schema-registry:
image: confluentinc/cp-schema-registry:7.4.0
ports:
- "8081:8081"
environment:
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: kafka:9092
```
## Testing
### Unit Testing
```typescript
import { EventPublisher } from '../event-publisher';
import { producer } from '../../config/kafka.config';
jest.mock('../../config/kafka.config');
describe('EventPublisher', () => {
it('should publish event successfully', async () => {
const publisher = new EventPublisher();
const mockSend = jest.fn().mockResolvedValue({});
(producer.send as jest.Mock) = mockSend;
await publisher.publish('user.created', {
eventType: 'user.created',
eventVersion: '1.0.0',
data: { userId: '123' },
});
expect(mockSend).toHaveBeenCalled();
});
});
```
### Integration Testing with Test Containers
```typescript
import { KafkaContainer } from '@testcontainers/kafka';
describe('Event Flow E2E', () => {
let kafkaContainer: StartedKafkaContainer;
beforeAll(async () => {
kafkaContainer = await new KafkaContainer().start();
process.env.KAFKA_BROKERS = kafkaContainer.getBootstrapServer();
});
it('should publish and consume event', async () => {
// Test implementation
});
});
```
## Common Use Cases
### User Created Event Flow
1. Auth Service creates user in database
2. Publishes `user.created` event to Kafka
3. Notification Service consumes event and sends welcome email
4. Analytics Service consumes event and updates metrics
### Order Processing with Multiple Consumers
1. Order Service publishes `order.placed` event
2. Payment Service processes payment
3. Inventory Service reserves items
4. Notification Service sends confirmation
## Related Skills
- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker, retry patterns
- [Error Handling Patterns](./error-handling-patterns.md) - Error handling best practices
- [Observability & Monitoring](./observability-monitoring.md) - Logging, metrics, tracing
- [Middleware Patterns](./middleware-patterns.md) - SSE endpoint middleware
- [Project Rules](./project-rules.md) - GoodGo coding standards
## Resources
- [KafkaJS Documentation](https://kafka.js.org/) - Node.js Kafka client
- [Confluent Schema Registry](https://docs.confluent.io/platform/current/schema-registry/index.html) - Schema versioning
- [Kafka Best Practices](https://kafka.apache.org/documentation/#best_practices) - Official Kafka documentation
- Skill Source: `.cursor/skills/event-driven-architecture/SKILL.md`

View File

@@ -0,0 +1,56 @@
---
name: infrastructure-as-code
description: Infrastructure as Code patterns for GoodGo platform including Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, and multi-environment management.
---
# Infrastructure as Code Patterns
## When to Use This Skill
Use this skill when:
- Managing infrastructure with code
- Implementing Terraform modules
- Setting up GitOps workflows
- Creating Kubernetes operators
- Testing infrastructure changes
## Key Patterns
### Terraform Modules
```hcl
# Reusable module
module "postgresql" {
source = "../../modules/postgresql"
database_name = "goodgo"
environment = "staging"
}
```
### GitOps with ArgoCD
```yaml
# Automated sync from Git
spec:
source:
repoURL: https://github.com/goodgo/platform
path: deployments/production/kubernetes
syncPolicy:
automated:
prune: true
selfHeal: true
```
## Best Practices
1. Keep all infrastructure in version control
2. Create reusable Terraform modules
3. Test infrastructure changes before applying
4. Use GitOps for Kubernetes deployments
5. Separate environments completely
## Resources
- [Terraform Documentation](https://www.terraform.io/docs)
- [Deployment Kubernetes](./deployment-kubernetes.md)
- Skill Source: `.cursor/skills/infrastructure-as-code/SKILL.md`

View File

@@ -0,0 +1,177 @@
---
name: inter-service-communication
description: Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
---
# Inter-Service Communication Patterns
## When to Use This Skill
Use this skill when:
- Implementing service-to-service communication
- Choosing between REST, gRPC, or GraphQL protocols
- Setting up gRPC services and clients
- Implementing GraphQL services and resolvers
- Implementing service-to-service authentication
- Building resilient service clients with circuit breakers
- Managing connection pooling for service clients
- Implementing request/response interceptors
- Handling service discovery for internal calls
- Optimizing inter-service communication performance
## Core Concepts
### Communication Protocol Options
**HTTP/REST:**
- Human-readable, easy to debug
- Browser-compatible
- Standard HTTP semantics
- JSON payloads
- Good for external APIs
**gRPC:**
- Binary protocol (Protocol Buffers)
- High performance, low latency
- Streaming support
- Strong typing with .proto files
- HTTP/2 based
**GraphQL:**
- Flexible query language
- Single endpoint
- Client-controlled data fetching
- Strong typing with schema
### Protocol Selection Guidelines
Choose protocol based on use case, performance requirements, team expertise, and ecosystem needs.
## Key Patterns
### HTTP/REST Service Client
```typescript
// Base service client with circuit breaker and interceptors
import { ServiceClient } from '../../core/clients/service-client';
const notificationClient = new ServiceClient({
baseURL: process.env.NOTIFICATION_SERVICE_URL || 'http://notification-service:5003',
serviceName: 'notification-service',
timeout: 5000,
enableCircuitBreaker: true,
});
// Usage
await notificationClient.post('/api/v1/notifications', {
userId,
message,
});
```
### gRPC Service
```typescript
// gRPC server implementation
import { UserGrpcServer } from './user.grpc.service';
const grpcServer = new UserGrpcServer(userService);
grpcServer.start(50051);
// gRPC client
import { GrpcClient } from '../../core/clients/grpc-client';
const userGrpcClient = new GrpcClient({
protoPath: './proto/user_service.proto',
packageName: 'goodgo.user.v1',
serviceName: 'UserService',
serverUrl: 'localhost:50051',
});
const user = await userGrpcClient.call('getUser', { user_id: '123' });
```
### GraphQL Service
```typescript
// GraphQL client
import { GraphQLServiceClient } from '../../core/clients/graphql-client';
const userGraphQLClient = new GraphQLServiceClient({
endpoint: 'http://user-service:5002/graphql',
});
const GET_USER_QUERY = `
query GetUser($id: ID!) {
user(id: $id) {
id
email
name
}
}
`;
const user = await userGraphQLClient.query(GET_USER_QUERY, { id: '123' });
```
### Service-to-Service Authentication
```typescript
// Internal auth middleware
import { internalAuthMiddleware } from '../../middlewares/internal-auth.middleware';
router.use('/internal', internalAuthMiddleware);
// Client automatically adds auth header
const client = new ServiceClient({
baseURL: 'http://service:5000',
serviceName: 'service',
});
// X-Service-Auth header is added automatically
```
## Best Practices
### Protocol Selection
- **REST**: External APIs, browser clients, simple CRUD
- **gRPC**: Internal services, high performance, streaming
- **GraphQL**: Complex queries, mobile apps, flexible data
### Performance
- Use connection pooling
- Enable HTTP keep-alive
- Set appropriate timeouts
- Implement circuit breakers
### Security
- Always authenticate internal calls
- Use TLS/mTLS
- Store secrets securely
- Implement rate limiting
### Observability
- Log with correlation IDs
- Track metrics (duration, success rate)
- Add distributed tracing
- Monitor service health
## Testing
```typescript
// Mock service client
const mockClient = createMockServiceClient();
mockClient.get.mockResolvedValue({ id: '123' });
```
## Resources
- [gRPC Documentation](https://grpc.io/docs/)
- [GraphQL Documentation](https://graphql.org/learn/)
- [Protocol Buffers](https://developers.google.com/protocol-buffers)
- [Resilience Patterns](./resilience-patterns.md)
- [Security](./security.md)
- Skill Source: `.cursor/skills/inter-service-communication/SKILL.md`

View File

@@ -0,0 +1,62 @@
---
name: performance-optimization
description: Performance optimization patterns for GoodGo microservices including database query optimization, memory leak detection, profiling, connection pooling, and caching strategies.
---
# Performance Optimization Patterns
## When to Use This Skill
Use this skill when:
- Optimizing database queries
- Detecting and fixing memory leaks
- Profiling application performance
- Optimizing connection pooling
- Improving caching strategies
- Identifying N+1 query problems
## Key Patterns
### Database Query Optimization
```typescript
// Avoid N+1 queries
// Bad: Multiple queries
for (const user of users) {
user.orders = await orderRepository.findByUserId(user.id);
}
// Good: Single query with join
const users = await userRepository.findAll({
include: { orders: true },
});
```
### Memory Profiling
```typescript
// Monitor memory usage
const profiler = new MemoryProfiler();
profiler.start(); // Monitor every minute
```
### Batch Operations
```typescript
// Batch database operations
await batchOperations.batchCreate(items, 100); // Process 100 at a time
```
## Best Practices
1. Use indexes, avoid N+1 queries
2. Monitor memory usage, detect leaks
3. Cache frequently accessed data
4. Configure connection pools appropriately
5. Profile regularly to identify bottlenecks
## Resources
- [Caching Patterns](./caching-patterns.md)
- [Observability & Monitoring](./observability-monitoring.md)
- Skill Source: `.cursor/skills/performance-optimization/SKILL.md`

View File

@@ -0,0 +1,57 @@
---
name: service-discovery-registry
description: Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration.
---
# Service Discovery & Registry Patterns
## When to Use This Skill
Use this skill when:
- Implementing service discovery mechanisms
- Managing service registry
- Orchestrating health checks
- Implementing load balancing strategies
- Integrating with service mesh
## Key Patterns
### Kubernetes DNS Discovery
```typescript
// Use Kubernetes DNS for service discovery
const serviceUrl = `http://user-service.production.svc.cluster.local`;
```
### Service Registry
```typescript
// Register service
await serviceRegistry.register({
name: 'user-service',
url: 'http://user-service:5000',
status: 'healthy',
});
// Discover service
const service = await serviceRegistry.discover('user-service');
```
### Health Check Aggregation
```typescript
// Aggregate health from multiple services
const health = await healthAggregator.getAggregatedHealth();
```
## Best Practices
1. Use Kubernetes DNS for service discovery
2. Implement comprehensive health checks
3. Use service registry for dynamic services
4. Choose appropriate load balancing strategy
## Resources
- [Deployment Kubernetes](./deployment-kubernetes.md)
- Skill Source: `.cursor/skills/service-discovery-registry/SKILL.md`

View File

@@ -11,7 +11,7 @@ Cursor Skills là các module kiến thức chuyên biệt hướng dẫn AI ass
## Các Skills Có Sẵn
GoodGo platform bao gồm **15 Cursor Skills** được tổ chức theo danh mục:
GoodGo platform bao gồm **25 Cursor Skills** được tổ chức theo danh mục:
### API & Data Layer
@@ -69,6 +69,36 @@ Kubernetes deployment patterns for GoodGo microservices. Use when deploying to s
Kubernetes deployment patterns cho GoodGo microservices. Sử dụng khi deploy lên staging/production, tạo K8s manifests, config HPA, setup ingress, hoặc troubleshoot K8s deployments.
#### [Event-Driven Architecture](./event-driven-architecture.md)
Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
Các patterns kiến trúc hướng sự kiện với Apache Kafka cho GoodGo microservices. Sử dụng khi implement giao tiếp bất đồng bộ, publish/consume events, event sourcing, CQRS, hoặc tích hợp event streams với HTTP endpoints.
#### [Inter-Service Communication](./inter-service-communication.md)
Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
Các patterns giao tiếp giữa services cho GoodGo microservices bao gồm gRPC, GraphQL, service-to-service authentication, lựa chọn protocol, và client patterns. Sử dụng khi implement service-to-service calls, chọn communication protocols, hoặc xây dựng service clients.
#### [Data Consistency Patterns](./data-consistency-patterns.md)
Data consistency patterns for distributed microservices including Saga patterns, distributed transactions, eventual consistency, compensation, and idempotency. Use when handling distributed transactions, implementing eventual consistency, or managing data synchronization across services.
Các patterns nhất quán dữ liệu cho distributed microservices bao gồm Saga patterns, distributed transactions, eventual consistency, compensation, và idempotency. Sử dụng khi xử lý distributed transactions, implement eventual consistency, hoặc quản lý đồng bộ dữ liệu giữa các services.
#### [API Gateway Advanced](./api-gateway-advanced.md)
Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience. Use when implementing API aggregation, service composition, or advanced gateway features.
Các patterns API Gateway nâng cao cho GoodGo microservices bao gồm API composition, request/response transformation, tích hợp service mesh, routing nâng cao, và resilience ở gateway level. Sử dụng khi implement API aggregation, service composition, hoặc các tính năng gateway nâng cao.
#### [Configuration Management](./configuration-management.md)
Configuration management patterns for GoodGo microservices including feature flags, dynamic configuration reloading, environment-specific configurations, and secrets management. Use when implementing feature toggles, managing configuration, or handling environment variables.
Các patterns quản lý cấu hình cho GoodGo microservices bao gồm feature flags, dynamic configuration reloading, environment-specific configurations, và secrets management. Sử dụng khi implement feature toggles, quản lý configuration, hoặc xử lý environment variables.
#### [Performance Optimization](./performance-optimization.md)
Performance optimization patterns for GoodGo microservices including database query optimization, memory leak detection, profiling, connection pooling, and caching strategies. Use when optimizing performance, profiling applications, or detecting performance bottlenecks.
Các patterns tối ưu hiệu suất cho GoodGo microservices bao gồm tối ưu database queries, phát hiện memory leaks, profiling, connection pooling, và caching strategies. Sử dụng khi tối ưu hiệu suất, profiling ứng dụng, hoặc phát hiện performance bottlenecks.
#### [Observability & Monitoring](./observability-monitoring.md)
Observability and monitoring patterns for GoodGo microservices. Use when adding metrics, implementing logging, setting up tracing, creating health checks, or debugging production issues.
@@ -84,6 +114,26 @@ Standard development process for creating and maintaining microservices in GoodG
Quy trình phát triển chuẩn để tạo và duy trì microservices trong nền tảng GoodGo. Sử dụng khi tạo services mới, migrate services, refactor services, hoặc lập kế hoạch implement services.
#### [CI/CD Advanced Patterns](./cicd-advanced-patterns.md)
Advanced CI/CD patterns for GoodGo microservices including blue-green deployments, canary releases, automated rollback, deployment verification, and progressive delivery. Use when implementing advanced deployment strategies, automated rollbacks, or progressive delivery pipelines.
Các patterns CI/CD nâng cao cho GoodGo microservices bao gồm blue-green deployments, canary releases, automated rollback, deployment verification, và progressive delivery. Sử dụng khi implement các chiến lược deployment nâng cao, automated rollbacks, hoặc progressive delivery pipelines.
#### [Infrastructure as Code](./infrastructure-as-code.md)
Infrastructure as Code patterns for GoodGo platform including Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, and multi-environment management. Use when managing infrastructure, implementing GitOps, or creating reusable infrastructure modules.
Các patterns Infrastructure as Code cho nền tảng GoodGo bao gồm Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, và multi-environment management. Sử dụng khi quản lý infrastructure, implement GitOps, hoặc tạo các infrastructure modules tái sử dụng.
#### [API Versioning Strategy](./api-versioning-strategy.md)
API versioning strategies for GoodGo microservices including semantic versioning, backward compatibility patterns, API deprecation, version negotiation, and breaking changes handling. Use when versioning APIs, handling breaking changes, or implementing API deprecation strategies.
Các chiến lược versioning API cho GoodGo microservices bao gồm semantic versioning, backward compatibility patterns, API deprecation, version negotiation, và xử lý breaking changes. Sử dụng khi versioning APIs, xử lý breaking changes, hoặc implement API deprecation strategies.
#### [Service Discovery & Registry](./service-discovery-registry.md)
Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration. Use when implementing service discovery, managing service health, or integrating with service mesh.
Các patterns service discovery và registry cho GoodGo microservices bao gồm service registry, health check orchestration, load balancing strategies, và tích hợp service mesh. Sử dụng khi implement service discovery, quản lý service health, hoặc tích hợp với service mesh.
### Standards & Security
#### [Project Rules](./project-rules.md)
@@ -115,6 +165,12 @@ Hướng dẫn viết technical documentation trong dự án GoodGo. Sử dụng
| Viết documentation | Documentation, Comment Code |
| Implement authentication | Security, API Design, Database & Prisma |
| Optimize database queries | Database & Prisma, Observability |
| Implement event-driven communication | Event-Driven Architecture, Resilience Patterns |
| Implement service-to-service calls | Inter-Service Communication, Security, Resilience Patterns |
| Handle distributed transactions | Data Consistency Patterns, Event-Driven Architecture |
| Optimize performance | Performance Optimization, Observability & Monitoring |
| Manage feature flags | Configuration Management |
| Deploy with zero downtime | CI/CD Advanced Patterns, Deployment Kubernetes |
### Phụ Thuộc Giữa Các Skills
@@ -143,6 +199,39 @@ Application Layer
└── Error Handling Patterns
Infrastructure
├── Event-Driven Architecture
│ ├── Resilience Patterns
│ ├── Error Handling Patterns
│ └── Observability & Monitoring
├── Inter-Service Communication
│ ├── API Design
│ ├── Security
│ └── Resilience Patterns
├── Data Consistency Patterns
│ ├── Event-Driven Architecture
│ ├── Database & Prisma
│ └── Error Handling Patterns
├── API Gateway Advanced
│ ├── Middleware Patterns
│ ├── Security
│ └── API Design
├── Configuration Management
│ └── Observability & Monitoring
├── Performance Optimization
│ ├── Database & Prisma
│ ├── Caching Patterns
│ └── Observability & Monitoring
├── CI/CD Advanced Patterns
│ ├── Deployment Kubernetes
│ └── Testing Patterns
├── Infrastructure as Code
│ └── Deployment Kubernetes
├── API Versioning Strategy
│ ├── API Design
│ └── Middleware Patterns
├── Service Discovery & Registry
│ ├── Deployment Kubernetes
│ └── Observability & Monitoring
└── Resilience Patterns
├── Error Handling Patterns
└── Service Layer Patterns

View File

@@ -0,0 +1,45 @@
# API Gateway Nâng Cao (API Gateway Advanced)
Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience.
> Các patterns API Gateway nâng cao cho GoodGo microservices bao gồm API composition, request/response transformation, tích hợp service mesh, routing nâng cao, và resilience ở gateway level.
## Tổng Quan
Advanced API Gateway patterns extend basic gateway functionality with composition, transformation, service mesh integration, and gateway-level resilience patterns.
Các patterns API Gateway nâng cao mở rộng chức năng gateway cơ bản với composition, transformation, tích hợp service mesh, và các resilience patterns ở gateway level.
## Khi Nào Sử Dụng
Use this skill when implementing API composition, request/response transformation, or service mesh integration.
Sử dụng skill này khi implement API composition, request/response transformation, hoặc tích hợp service mesh.
## Các Patterns Chính
### API Composition / API Composition
```typescript
// EN: Aggregate multiple service responses
// VI: Tổng hợp responses từ nhiều services
const [user, orders, payments] = await Promise.all([
userClient.get(`/users/${userId}`),
orderClient.get(`/orders?userId=${userId}`),
paymentClient.get(`/payments?userId=${userId}`),
]);
```
## Best Practices / Thực Hành Tốt
1. Use API composition for aggregating related data / Sử dụng API composition để tổng hợp dữ liệu liên quan
2. Cache at gateway / Cache ở gateway
3. Implement circuit breaker at gateway / Implement circuit breaker ở gateway
## Skills Liên Quan
- [Middleware Patterns](./middleware-patterns.md) - Middleware patterns / Các patterns middleware
- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker / Circuit breaker
## Tài Nguyên
- Skill Source: `.cursor/skills/api-gateway-advanced/SKILL.md`

View File

@@ -0,0 +1,46 @@
# Chiến Lược Versioning API (API Versioning Strategy)
API versioning strategies for GoodGo microservices including semantic versioning, backward compatibility patterns, API deprecation, version negotiation, and breaking changes handling.
> Các chiến lược versioning API cho GoodGo microservices bao gồm semantic versioning, backward compatibility patterns, API deprecation, version negotiation, và xử lý breaking changes.
## Tổng Quan
API versioning strategies enable managing API evolution while maintaining compatibility and clearly communicating changes to consumers.
Các chiến lược versioning API cho phép quản lý sự phát triển API đồng thời duy trì tương thích và giao tiếp rõ ràng các thay đổi tới consumers.
## Khi Nào Sử Dụng
Use this skill when versioning APIs, handling breaking changes, or implementing deprecation.
Sử dụng skill này khi versioning APIs, xử lý breaking changes, hoặc implement deprecation.
## Các Patterns Chính
### URL Path Versioning / Versioning Theo Đường Dẫn
```typescript
// EN: Version routes
// VI: Routes theo version
router.use('/v1', v1Router);
router.use('/v2', v2Router);
```
### Deprecation / Deprecation
```typescript
// EN: Deprecation headers
// VI: Headers deprecation
res.setHeader('Deprecation', 'true');
res.setHeader('Sunset', '2024-12-31');
```
## Best Practices / Thực Hành Tốt
1. Choose strategy and be consistent / Chọn chiến lược và nhất quán
2. Use semantic versioning / Sử dụng semantic versioning
3. Always deprecate before removing / Luôn deprecate trước khi xóa
## Tài Nguyên
- Skill Source: `.cursor/skills/api-versioning-strategy/SKILL.md`

View File

@@ -0,0 +1,48 @@
# CI/CD Patterns Nâng Cao (CI/CD Advanced Patterns)
Advanced CI/CD patterns for GoodGo microservices including blue-green deployments, canary releases, automated rollback, deployment verification, and progressive delivery.
> Các patterns CI/CD nâng cao cho GoodGo microservices bao gồm blue-green deployments, canary releases, automated rollback, deployment verification, và progressive delivery.
## Tổng Quan
Advanced CI/CD patterns enable safe, zero-downtime deployments with blue-green, canary releases, automated rollbacks, and deployment verification.
Các patterns CI/CD nâng cao cho phép deployments an toàn, zero-downtime với blue-green, canary releases, automated rollbacks, và deployment verification.
## Khi Nào Sử Dụng
Use this skill when implementing advanced deployment strategies, automated rollbacks, or progressive delivery.
Sử dụng skill này khi implement các chiến lược deployment nâng cao, automated rollbacks, hoặc progressive delivery.
## Các Patterns Chính
### Blue-Green Deployment / Blue-Green Deployment
```yaml
# EN: Switch between blue and green environments
# VI: Chuyển đổi giữa blue và green environments
spec:
selector:
version: blue # EN: Switch to green / VI: Chuyển sang green
```
### Canary Deployment / Canary Deployment
```yaml
# EN: Gradual rollout to subset of users
# VI: Rollout dần dần tới subset users
route:
- destination: { subset: canary }
weight: 10 # EN: 10% traffic / VI: 10% traffic
```
## Best Practices / Thực Hành Tốt
1. Use blue-green for zero-downtime / Sử dụng blue-green cho zero-downtime
2. Use canary for gradual rollouts / Sử dụng canary cho rollouts dần dần
3. Always have rollback plan / Luôn có kế hoạch rollback
## Tài Nguyên
- Skill Source: `.cursor/skills/cicd-advanced-patterns/SKILL.md`

View File

@@ -0,0 +1,45 @@
# Quản Lý Cấu Hình (Configuration Management)
Configuration management patterns for GoodGo microservices including feature flags, dynamic configuration reloading, environment-specific configurations, and secrets management.
> Các patterns quản lý cấu hình cho GoodGo microservices bao gồm feature flags, dynamic configuration reloading, environment-specific configurations, và secrets management.
## Tổng Quan
Configuration management patterns enable flexible, secure, and environment-aware configuration handling with feature flags, dynamic reloading, and secrets management.
Các patterns quản lý cấu hình cho phép xử lý cấu hình linh hoạt, an toàn và nhận biết environment với feature flags, dynamic reloading, và quản lý secrets.
## Khi Nào Sử Dụng
Use this skill when implementing feature flags, managing configurations, or handling secrets.
Sử dụng skill này khi implement feature flags, quản lý configurations, hoặc xử lý secrets.
## Các Patterns Chính
### Feature Flags / Feature Flags
```typescript
// EN: Check if feature is enabled
// VI: Kiểm tra xem feature có được bật không
const enabled = await featureFlagService.isEnabled('new-feature', userId);
```
### Dynamic Configuration / Configuration Động
```typescript
// EN: Auto-reload configuration
// VI: Tự động tải lại configuration
await configService.load();
configService.startAutoReload(60000);
```
## Best Practices / Thực Hành Tốt
1. Always validate configuration / Luôn validate configuration
2. Never commit secrets / Không bao giờ commit secrets
3. Use feature flags for rollouts / Sử dụng feature flags cho rollouts
## Tài Nguyên
- Skill Source: `.cursor/skills/configuration-management/SKILL.md`

View File

@@ -0,0 +1,84 @@
# Patterns Nhất Quán Dữ Liệu (Data Consistency Patterns)
Data consistency patterns for distributed microservices including Saga patterns, distributed transactions, eventual consistency, compensation, and idempotency. Use when handling distributed transactions, implementing eventual consistency, or managing data synchronization across services.
> Các patterns nhất quán dữ liệu cho distributed microservices bao gồm Saga patterns, distributed transactions, eventual consistency, compensation, và idempotency. Sử dụng khi xử lý distributed transactions, implement eventual consistency, hoặc quản lý đồng bộ dữ liệu giữa các services.
## Tổng Quan
Data consistency in distributed systems requires different approaches than traditional ACID transactions. This skill covers Saga patterns for distributed transactions, idempotency for retries, optimistic locking for conflicts, and eventual consistency strategies.
Nhất quán dữ liệu trong hệ thống phân tán yêu cầu các cách tiếp cận khác với ACID transactions truyền thống. Skill này bao gồm Saga patterns cho distributed transactions, idempotency cho retries, optimistic locking cho conflicts, và các chiến lược eventual consistency.
## Khi Nào Sử Dụng
Use this skill when:
- Implementing distributed transactions across multiple services
- Handling eventual consistency in microservices
- Implementing Saga patterns for distributed workflows
- Designing compensation strategies
Sử dụng skill này khi:
- Implement distributed transactions qua nhiều services
- Xử lý eventual consistency trong microservices
- Implement Saga patterns cho distributed workflows
- Thiết kế chiến lược compensation
## Khái Niệm Chính
### ACID vs BASE
**ACID (Truyền Thống)**: Atomicity, Consistency, Isolation, Durability
**BASE (Phân Tán)**: Basic Availability, Soft state, Eventual consistency
### Các Mô Hình Nhất Quán
- **Strong Consistency**: Tất cả nodes thấy cùng dữ liệu cùng lúc
- **Eventual Consistency**: Hệ thống trở nên nhất quán theo thời gian
- **Weak Consistency**: Không đảm bảo về thời điểm nhất quán
## Các Patterns Chính
### Saga Orchestrator Pattern
```typescript
// EN: Centralized orchestrator coordinates steps
// VI: Orchestrator tập trung điều phối các bước
const saga = new SagaOrchestrator();
await saga.execute({
sagaId: 'saga_123',
steps: [
{ name: 'create-order', execute: createOrder, compensate: cancelOrder },
{ name: 'reserve-inventory', execute: reserveInventory, compensate: releaseInventory },
],
});
```
### Idempotency / Idempotency
```typescript
// EN: Execute with idempotency check
// VI: Thực thi với idempotency check
await idempotencyHandler.execute(
idempotencyKey,
async () => await userService.create(data)
);
```
## Best Practices / Thực Hành Tốt
1. **Design Compensations**: Mỗi step cần compensation / Every step needs compensation
2. **Idempotent Steps**: Làm cho steps idempotent cho retries / Make steps idempotent for retries
3. **Conflict Resolution**: Định nghĩa chiến lược giải quyết / Define resolution strategies
4. **Monitoring**: Theo dõi saga execution / Track saga execution
## Skills Liên Quan
- [Event-Driven Architecture](./event-driven-architecture.md) - Event patterns / Các patterns event
- [Error Handling Patterns](./error-handling-patterns.md) - Error handling / Xử lý lỗi
- [Database & Prisma](./database-prisma.md) - Database patterns / Các patterns database
## Tài Nguyên
- [Saga Pattern](https://microservices.io/patterns/data/saga.html) - Saga pattern overview
- Skill Source: `.cursor/skills/data-consistency-patterns/SKILL.md` - Source file đầy đủ

View File

@@ -0,0 +1,381 @@
# Kiến Trúc Hướng Sự Kiện (Event-Driven Architecture)
Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
> Các patterns kiến trúc hướng sự kiện với Apache Kafka cho GoodGo microservices. Sử dụng khi implement giao tiếp bất đồng bộ, publish/consume events, event sourcing, CQRS, hoặc tích hợp event streams với HTTP endpoints.
## Tổng Quan
Event-Driven Architecture (EDA) enables asynchronous communication between services using Apache Kafka as the message broker. This pattern decouples services, improves scalability, and enables event sourcing, CQRS, and reactive systems. GoodGo platform uses Kafka for high-throughput event streaming and integrates with Traefik to expose events via SSE/WebSocket endpoints.
Kiến trúc hướng sự kiện (EDA) cho phép giao tiếp bất đồng bộ giữa các services sử dụng Apache Kafka làm message broker. Pattern này tách biệt các services, cải thiện khả năng mở rộng, và cho phép event sourcing, CQRS, và các hệ thống reactive. Nền tảng GoodGo sử dụng Kafka cho event streaming hiệu suất cao và tích hợp với Traefik để expose events qua SSE/WebSocket endpoints.
## Khi Nào Sử Dụng
Use this skill when:
- Implementing asynchronous communication between services
- Decoupling services for better scalability
- Publishing domain events for downstream consumers
- Consuming events from other services
- Implementing event sourcing patterns
- Implementing CQRS (Command Query Responsibility Segregation)
- Exposing event streams via HTTP (SSE/WebSocket)
- Handling eventual consistency across services
- Building reactive systems that respond to changes
- Integrating with Apache Kafka message broker
Sử dụng skill này khi:
- Implement giao tiếp bất đồng bộ giữa các services
- Tách biệt services để cải thiện khả năng mở rộng
- Publish domain events cho downstream consumers
- Consume events từ các services khác
- Implement event sourcing patterns
- Implement CQRS (Command Query Responsibility Segregation)
- Expose event streams qua HTTP (SSE/WebSocket)
- Xử lý eventual consistency giữa các services
- Xây dựng reactive systems phản hồi với các thay đổi
- Tích hợp với Apache Kafka message broker
## Khái Niệm Chính
### Event-Driven vs Request-Response
**Request-Response (Synchronous / Đồng Bộ):**
- Client waits for response / Client đợi response
- Tight coupling between services / Liên kết chặt chẽ giữa các services
- Blocking operations / Các thao tác blocking
- Immediate consistency / Nhất quán ngay lập tức
- Use Traefik API Gateway for HTTP/REST / Sử dụng Traefik API Gateway cho HTTP/REST
**Event-Driven (Asynchronous / Bất Đồng Bộ):**
- Fire-and-forget publishing / Publish fire-and-forget
- Loose coupling between services / Liên kết lỏng lẻo giữa các services
- Non-blocking operations / Các thao tác non-blocking
- Eventual consistency / Nhất quán cuối cùng
- Use Kafka for message broker / Sử dụng Kafka cho message broker
### Kafka Fundamentals / Các Khái Niệm Cơ Bản về Kafka
- **Topics**: Named streams of events (e.g., `user.created`, `order.placed`) / Các luồng sự kiện được đặt tên
- **Partitions**: Physical division of topics for parallelism and scaling / Chia nhỏ vật lý của topics để song song hóa và mở rộng
- **Consumer Groups**: Groups of consumers that work together to process events / Các nhóm consumers làm việc cùng nhau để xử lý events
- **Producers**: Services that publish events to topics / Services phát hành events tới topics
- **Consumers**: Services that subscribe to topics and process events / Services đăng ký topics và xử lý events
### Traefik Integration / Tích Hợp Traefik
Traefik serves dual purpose:
- **API Gateway**: Routes synchronous HTTP/REST requests / Định tuyến các request HTTP/REST đồng bộ
- **Event Streaming Gateway**: Routes SSE/WebSocket connections to event streaming endpoints / Định tuyến các kết nối SSE/WebSocket tới event streaming endpoints
Services publish events to Kafka, then expose SSE/WebSocket endpoints that consume from Kafka for HTTP clients.
Services publish events vào Kafka, sau đó expose SSE/WebSocket endpoints consume từ Kafka cho HTTP clients.
## Các Patterns Chính
### Event Publishing / Phát Hành Events
```typescript
// src/core/events/event-publisher.ts
import { producer } from '../config/kafka.config';
import { logger } from '@goodgo/logger';
import { v4 as uuidv4 } from 'uuid';
export class EventPublisher {
/**
* EN: Publish event to Kafka topic
* VI: Phát hành event tới Kafka topic
*/
async publish<T extends BaseEvent>(
topic: string,
event: Omit<T, 'eventId' | 'timestamp' | 'source'>,
options?: { partitionKey?: string }
): Promise<void> {
const fullEvent: T = {
...event,
eventId: uuidv4(),
timestamp: new Date().toISOString(),
source: this.serviceName,
} as T;
await producer.send({
topic,
messages: [{
key: options?.partitionKey || fullEvent.eventId,
value: JSON.stringify(fullEvent),
headers: {
'event-type': event.eventType,
'event-version': event.eventVersion,
},
}],
});
}
}
```
**Tham Khảo**: `.cursor/skills/event-driven-architecture/SKILL.md`
### Event Consuming / Tiêu Thụ Events
```typescript
// src/core/events/event-consumer.ts
import { kafka } from '../config/kafka.config';
export class EventConsumer {
private handlers: Map<string, EventHandler[]> = new Map();
/**
* EN: Register event handler
* VI: Đăng ký event handler
*/
on<T extends BaseEvent>(eventType: string, handler: EventHandler<T>): void {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, []);
}
this.handlers.get(eventType)!.push(handler);
}
/**
* EN: Start consuming from topics
* VI: Bắt đầu consume từ topics
*/
async start(topics: string[]): Promise<void> {
await this.consumer.connect();
await this.consumer.subscribe({ topics, fromBeginning: false });
await this.consumer.run({
eachMessage: async ({ topic, partition, message }) => {
const event: BaseEvent = JSON.parse(message.value?.toString() || '{}');
const handlers = this.handlers.get(event.eventType) || [];
await Promise.all(handlers.map(h => h.handle(event)));
},
});
}
}
```
### Outbox Pattern / Pattern Outbox
The Outbox pattern ensures transactional event publishing by storing events in the database within the same transaction as the business data.
Pattern Outbox đảm bảo publish events trong transaction bằng cách lưu events trong database trong cùng transaction với business data.
```typescript
// EN: Store event in database within transaction
// VI: Lưu event vào database trong transaction
await prisma.outboxEvent.create({
data: {
eventType: 'user.created',
eventData: userData,
topic: 'user.created',
status: 'PENDING',
},
});
// EN: Separate process publishes from outbox to Kafka
// VI: Process riêng publish từ outbox tới Kafka
async function processOutbox() {
const events = await prisma.outboxEvent.findMany({
where: { status: 'PENDING' },
});
for (const event of events) {
await eventPublisher.publish(event.topic, event.eventData);
await prisma.outboxEvent.update({
where: { id: event.id },
data: { status: 'PUBLISHED' },
});
}
}
```
### SSE Endpoint / Endpoint SSE
Server-Sent Events (SSE) allows clients to receive event streams via HTTP.
Server-Sent Events (SSE) cho phép clients nhận event streams qua HTTP.
```typescript
// src/modules/events/events.controller.ts
async streamEvents(req: Request, res: Response): Promise<void> {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
const topic = req.query.topic as string;
const consumer = kafka.consumer({ groupId: `sse-${Date.now()}` });
await consumer.connect();
await consumer.subscribe({ topic, fromBeginning: false });
await consumer.run({
eachMessage: async ({ message }) => {
const event = JSON.parse(message.value?.toString() || '{}');
res.write(`data: ${JSON.stringify(event)}\n\n`);
},
});
req.on('close', async () => {
await consumer.disconnect();
});
}
```
## Cấu Trúc Event / Event Structure
```typescript
interface BaseEvent {
eventId: string; // EN: Unique event identifier / VI: Định danh event duy nhất
eventType: string; // EN: Event type (e.g., "user.created") / VI: Loại event
eventVersion: string; // EN: Schema version / VI: Phiên bản schema
timestamp: string; // EN: ISO 8601 timestamp / VI: Timestamp ISO 8601
source: string; // EN: Service that published the event / VI: Service phát hành event
correlationId?: string; // EN: Request correlation ID / VI: Correlation ID của request
traceId?: string; // EN: Distributed tracing ID / VI: ID phân tán tracing
data: unknown; // EN: Event payload / VI: Payload của event
}
```
## Best Practices / Thực Hành Tốt
### Event Naming Conventions / Quy Ước Đặt Tên Events
- **Event Type**: `{domain}.{action}.v{version}` (e.g., `user.created.v1`) / Loại Event: `{domain}.{action}.v{version}`
- **Topic**: `{domain}.{entity}.{action}` (e.g., `user.created`) / Topic: `{domain}.{entity}.{action}`
- Use lowercase with dots as separators / Sử dụng chữ thường với dấu chấm làm phân cách
- Keep names descriptive and consistent / Giữ tên mô tả và nhất quán
### Partition Key Selection / Lựa Chọn Partition Key
- Use entity ID for ordering guarantees (same entity → same partition) / Sử dụng entity ID để đảm bảo thứ tự
- Use correlation ID for request tracing / Sử dụng correlation ID để trace request
- Use user ID for user-scoped events / Sử dụng user ID cho events phạm vi user
- Avoid high-cardinality keys (distributes evenly) / Tránh keys có độ phân tán cao
### Event Ordering Guarantees / Đảm Bảo Thứ Tự Events
- Kafka guarantees ordering **per partition** / Kafka đảm bảo thứ tự **theo partition**
- Use partition key to ensure related events go to same partition / Sử dụng partition key để đảm bảo events liên quan cùng partition
- Events in different partitions have no ordering guarantee / Events ở các partitions khác nhau không có đảm bảo thứ tự
- Don't rely on global ordering across all events / Không phụ thuộc vào thứ tự toàn cục
### Error Handling / Xử Lý Lỗi
- Implement Dead Letter Queue (DLQ) for failed events / Implement DLQ cho events failed
- Use retry with exponential backoff / Sử dụng retry với exponential backoff
- Log all event processing failures / Ghi log tất cả lỗi xử lý events
- Monitor consumer lag and DLQ size / Giám sát consumer lag và kích thước DLQ
### Observability / Khả Năng Quan Sát
- Log all published and consumed events / Ghi log tất cả events đã publish và consume
- Track metrics: events published/consumed, processing duration, consumer lag / Theo dõi metrics: events published/consumed, thời gian xử lý, consumer lag
- Add distributed tracing to event flows / Thêm distributed tracing vào event flows
- Include correlation IDs for request tracking / Bao gồm correlation IDs để theo dõi request
## Infrastructure Setup / Thiết Lập Hạ Tầng
### Docker Compose (Local / Cục Bộ)
```yaml
services:
kafka:
image: confluentinc/cp-kafka:7.4.0
ports:
- "9092:9092"
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
schema-registry:
image: confluentinc/cp-schema-registry:7.4.0
ports:
- "8081:8081"
environment:
SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: kafka:9092
```
**Tham Khảo**: `deployments/local/docker-compose.yml`
## Testing / Kiểm Thử
### Unit Testing / Kiểm Thử Đơn Vị
```typescript
import { EventPublisher } from '../event-publisher';
import { producer } from '../../config/kafka.config';
jest.mock('../../config/kafka.config');
describe('EventPublisher', () => {
it('should publish event successfully', async () => {
const publisher = new EventPublisher();
const mockSend = jest.fn().mockResolvedValue({});
(producer.send as jest.Mock) = mockSend;
await publisher.publish('user.created', {
eventType: 'user.created',
eventVersion: '1.0.0',
data: { userId: '123' },
});
expect(mockSend).toHaveBeenCalled();
});
});
```
### Integration Testing / Kiểm Thử Tích Hợp
Use Kafka test containers for integration testing:
Sử dụng Kafka test containers cho integration testing:
```typescript
import { KafkaContainer } from '@testcontainers/kafka';
describe('Event Flow E2E', () => {
let kafkaContainer: StartedKafkaContainer;
beforeAll(async () => {
kafkaContainer = await new KafkaContainer().start();
process.env.KAFKA_BROKERS = kafkaContainer.getBootstrapServer();
});
it('should publish and consume event', async () => {
// EN: Test implementation
// VI: Implementation test
});
});
```
## Use Cases / Các Trường Hợp Sử Dụng
### User Created Event Flow / Luồng User Created Event
1. Auth Service creates user in database / Auth Service tạo user trong database
2. Publishes `user.created` event to Kafka / Publish event `user.created` tới Kafka
3. Notification Service consumes event and sends welcome email / Notification Service consume event và gửi email chào mừng
4. Analytics Service consumes event and updates metrics / Analytics Service consume event và cập nhật metrics
### Order Processing with Multiple Consumers / Xử Lý Order với Nhiều Consumers
1. Order Service publishes `order.placed` event / Order Service publish event `order.placed`
2. Payment Service processes payment / Payment Service xử lý thanh toán
3. Inventory Service reserves items / Inventory Service dự trữ items
4. Notification Service sends confirmation / Notification Service gửi xác nhận
## Skills Liên Quan
- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker, retry patterns / Circuit breaker, các patterns retry
- [Error Handling Patterns](./error-handling-patterns.md) - Error handling best practices / Best practices về error handling
- [Observability & Monitoring](./observability-monitoring.md) - Logging, metrics, tracing / Logging, metrics, tracing
- [Middleware Patterns](./middleware-patterns.md) - SSE endpoint middleware / Middleware SSE endpoint
- [Project Rules](./project-rules.md) - GoodGo coding standards / Tiêu chuẩn coding GoodGo
## Tài Nguyên
- [KafkaJS Documentation](https://kafka.js.org/) - Node.js Kafka client
- [Confluent Schema Registry](https://docs.confluent.io/platform/current/schema-registry/index.html) - Schema versioning
- [Kafka Best Practices](https://kafka.apache.org/documentation/#best_practices) - Official Kafka documentation / Tài liệu chính thức Kafka
- Skill Source: `.cursor/skills/event-driven-architecture/SKILL.md` - Source file đầy đủ / Full source file

View File

@@ -0,0 +1,50 @@
# Infrastructure as Code
Infrastructure as Code patterns for GoodGo platform including Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, and multi-environment management.
> Các patterns Infrastructure as Code cho nền tảng GoodGo bao gồm Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, và multi-environment management.
## Tổng Quan
Infrastructure as Code enables managing infrastructure through code, providing version control, reproducibility, and automation.
Infrastructure as Code cho phép quản lý infrastructure qua code, cung cấp version control, reproducibility, và automation.
## Khi Nào Sử Dụng
Use this skill when managing infrastructure, implementing GitOps, or creating reusable modules.
Sử dụng skill này khi quản lý infrastructure, implement GitOps, hoặc tạo các modules tái sử dụng.
## Các Patterns Chính
### Terraform Modules / Terraform Modules
```hcl
# EN: Reusable module
# VI: Module tái sử dụng
module "postgresql" {
source = "../../modules/postgresql"
database_name = "goodgo"
}
```
### GitOps / GitOps
```yaml
# EN: Automated sync from Git
# VI: Đồng bộ tự động từ Git
spec:
syncPolicy:
automated:
prune: true
```
## Best Practices / Thực Hành Tốt
1. Keep infrastructure in version control / Giữ infrastructure trong version control
2. Create reusable modules / Tạo modules tái sử dụng
3. Test before applying / Test trước khi apply
## Tài Nguyên
- Skill Source: `.cursor/skills/infrastructure-as-code/SKILL.md`

View File

@@ -0,0 +1,196 @@
# Giao Tiếp Giữa Các Services (Inter-Service Communication)
Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
> Các patterns giao tiếp giữa services cho GoodGo microservices bao gồm gRPC, GraphQL, service-to-service authentication, lựa chọn protocol, và client patterns. Sử dụng khi implement service-to-service calls, chọn communication protocols, hoặc xây dựng service clients.
## Tổng Quan
Inter-service communication enables services to work together in a microservices architecture. GoodGo supports multiple protocols: HTTP/REST (current standard), gRPC (for high performance), and GraphQL (for flexible queries). This skill covers patterns for implementing resilient, secure, and performant inter-service communication.
Giao tiếp giữa các services cho phép các services làm việc cùng nhau trong kiến trúc microservices. GoodGo hỗ trợ nhiều protocols: HTTP/REST (chuẩn hiện tại), gRPC (cho hiệu suất cao), và GraphQL (cho queries linh hoạt). Skill này bao gồm các patterns để implement giao tiếp giữa services có khả năng phục hồi, bảo mật và hiệu suất cao.
## Khi Nào Sử Dụng
Use this skill when:
- Implementing service-to-service communication
- Choosing between REST, gRPC, or GraphQL protocols
- Setting up gRPC services and clients
- Implementing GraphQL services and resolvers
- Implementing service-to-service authentication
- Building resilient service clients with circuit breakers
Sử dụng skill này khi:
- Implement giao tiếp giữa các services
- Chọn giữa REST, gRPC, hoặc GraphQL protocols
- Setup gRPC services và clients
- Implement GraphQL services và resolvers
- Implement service-to-service authentication
- Xây dựng service clients có khả năng phục hồi với circuit breakers
## Khái Niệm Chính
### Các Lựa Chọn Protocol
**HTTP/REST:**
- Dễ đọc, dễ debug / Human-readable, easy to debug
- Tương thích browser / Browser-compatible
- Semantics HTTP chuẩn / Standard HTTP semantics
- JSON payloads
- Tốt cho external APIs / Good for external APIs
**gRPC:**
- Binary protocol (Protocol Buffers)
- Hiệu suất cao, độ trễ thấp / High performance, low latency
- Hỗ trợ streaming / Streaming support
- Strong typing với .proto files
- Dựa trên HTTP/2 / HTTP/2 based
**GraphQL:**
- Ngôn ngữ query linh hoạt / Flexible query language
- Single endpoint
- Client kiểm soát data fetching / Client-controlled data fetching
- Strong typing với schema
### Hướng Dẫn Lựa Chọn Protocol
Chọn protocol dựa trên use case, yêu cầu hiệu suất, chuyên môn team, và nhu cầu ecosystem.
Choose protocol based on use case, performance requirements, team expertise, and ecosystem needs.
## Các Patterns Chính
### HTTP/REST Service Client
```typescript
// EN: Service client với circuit breaker
// VI: Service client với circuit breaker
import { ServiceClient } from '../../core/clients/service-client';
const notificationClient = new ServiceClient({
baseURL: process.env.NOTIFICATION_SERVICE_URL || 'http://notification-service:5003',
serviceName: 'notification-service',
timeout: 5000,
enableCircuitBreaker: true,
});
// EN: Usage
// VI: Sử dụng
await notificationClient.post('/api/v1/notifications', {
userId,
message,
});
```
### gRPC Service
```typescript
// EN: gRPC server
// VI: gRPC server
import { UserGrpcServer } from './user.grpc.service';
const grpcServer = new UserGrpcServer(userService);
grpcServer.start(50051);
// EN: gRPC client
// VI: gRPC client
const userGrpcClient = new GrpcClient({
protoPath: './proto/user_service.proto',
packageName: 'goodgo.user.v1',
serviceName: 'UserService',
serverUrl: 'localhost:50051',
});
const user = await userGrpcClient.call('getUser', { user_id: '123' });
```
### GraphQL Service
```typescript
// EN: GraphQL client
// VI: GraphQL client
const userGraphQLClient = new GraphQLServiceClient({
endpoint: 'http://user-service:5002/graphql',
});
const GET_USER_QUERY = `
query GetUser($id: ID!) {
user(id: $id) {
id
email
name
}
}
`;
const user = await userGraphQLClient.query(GET_USER_QUERY, { id: '123' });
```
### Service-to-Service Authentication
```typescript
// EN: Internal auth middleware
// VI: Internal auth middleware
import { internalAuthMiddleware } from '../../middlewares/internal-auth.middleware';
router.use('/internal', internalAuthMiddleware);
// EN: Client tự động thêm auth header
// VI: Client automatically adds auth header
const client = new ServiceClient({
baseURL: 'http://service:5000',
serviceName: 'service',
});
// X-Service-Auth header được thêm tự động
```
## Best Practices / Thực Hành Tốt
### Protocol Selection / Lựa Chọn Protocol
- **REST**: External APIs, browser clients, simple CRUD / APIs ngoài, browser clients, CRUD đơn giản
- **gRPC**: Internal services, high performance, streaming / Services nội bộ, hiệu suất cao, streaming
- **GraphQL**: Complex queries, mobile apps, flexible data / Queries phức tạp, mobile apps, data linh hoạt
### Performance / Hiệu Suất
- Use connection pooling / Sử dụng connection pooling
- Enable HTTP keep-alive / Bật HTTP keep-alive
- Set appropriate timeouts / Thiết lập timeout phù hợp
- Implement circuit breakers / Implement circuit breakers
### Security / Bảo Mật
- Always authenticate internal calls / Luôn xác thực internal calls
- Use TLS/mTLS / Sử dụng TLS/mTLS
- Store secrets securely / Lưu secrets an toàn
- Implement rate limiting / Implement rate limiting
### Observability / Khả Năng Quan Sát
- Log with correlation IDs / Ghi log với correlation IDs
- Track metrics (duration, success rate) / Theo dõi metrics
- Add distributed tracing / Thêm distributed tracing
- Monitor service health / Giám sát sức khỏe service
## Testing / Kiểm Thử
```typescript
// EN: Mock service client
// VI: Mock service client
const mockClient = createMockServiceClient();
mockClient.get.mockResolvedValue({ id: '123' });
```
## Skills Liên Quan
- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker, retry patterns / Circuit breaker, các patterns retry
- [Security](./security.md) - Authentication, authorization / Authentication, authorization
- [API Design](./api-design.md) - RESTful API patterns / RESTful API patterns
- [Project Rules](./project-rules.md) - GoodGo coding standards / Tiêu chuẩn coding GoodGo
## Tài Nguyên
- [gRPC Documentation](https://grpc.io/docs/) - Tài liệu gRPC chính thức
- [GraphQL Documentation](https://graphql.org/learn/) - Tài liệu GraphQL
- [Protocol Buffers](https://developers.google.com/protocol-buffers) - Hướng dẫn Protocol Buffers
- Skill Source: `.cursor/skills/inter-service-communication/SKILL.md` - Source file đầy đủ

View File

@@ -0,0 +1,52 @@
# Tối Ưu Hiệu Suất (Performance Optimization)
Performance optimization patterns for GoodGo microservices including database query optimization, memory leak detection, profiling, connection pooling, and caching strategies.
> Các patterns tối ưu hiệu suất cho GoodGo microservices bao gồm tối ưu database queries, phát hiện memory leaks, profiling, connection pooling, và caching strategies.
## Tổng Quan
Performance optimization patterns help identify and fix performance bottlenecks, optimize database queries, detect memory leaks, and improve overall application performance.
Các patterns tối ưu hiệu suất giúp xác định và sửa các nút cổ chai hiệu suất, tối ưu database queries, phát hiện memory leaks, và cải thiện hiệu suất ứng dụng tổng thể.
## Khi Nào Sử Dụng
Use this skill when optimizing performance, profiling applications, or detecting bottlenecks.
Sử dụng skill này khi tối ưu hiệu suất, profiling ứng dụng, hoặc phát hiện bottlenecks.
## Các Patterns Chính
### Database Query Optimization / Tối Ưu Database Queries
```typescript
// EN: Avoid N+1 queries
// VI: Tránh N+1 queries
const users = await userRepository.findAll({
include: { orders: true }, // EN: Single query / VI: Single query
});
```
### Memory Profiling / Memory Profiling
```typescript
// EN: Monitor memory usage
// VI: Giám sát memory usage
const profiler = new MemoryProfiler();
profiler.start();
```
## Best Practices / Thực Hành Tốt
1. Use indexes, avoid N+1 queries / Sử dụng indexes, tránh N+1 queries
2. Monitor memory usage / Giám sát memory usage
3. Cache frequently accessed data / Cache dữ liệu thường truy cập
## Skills Liên Quan
- [Caching Patterns](./caching-patterns.md) - Caching strategies / Chiến lược caching
- [Observability & Monitoring](./observability-monitoring.md) - Monitoring / Giám sát
## Tài Nguyên
- Skill Source: `.cursor/skills/performance-optimization/SKILL.md`

View File

@@ -0,0 +1,45 @@
# Service Discovery & Registry
Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration.
> Các patterns service discovery và registry cho GoodGo microservices bao gồm service registry, health check orchestration, load balancing strategies, và tích hợp service mesh.
## Tổng Quan
Service discovery and registry patterns enable services to find and communicate with each other dynamically, with health monitoring and load balancing.
Các patterns service discovery và registry cho phép services tìm và giao tiếp với nhau một cách động, với giám sát health và load balancing.
## Khi Nào Sử Dụng
Use this skill when implementing service discovery, managing service registry, or orchestrating health checks.
Sử dụng skill này khi implement service discovery, quản lý service registry, hoặc điều phối health checks.
## Các Patterns Chính
### Kubernetes DNS Discovery / Service Discovery DNS Kubernetes
```typescript
// EN: Use Kubernetes DNS
// VI: Sử dụng Kubernetes DNS
const serviceUrl = `http://user-service.production.svc.cluster.local`;
```
### Service Registry / Service Registry
```typescript
// EN: Register and discover services
// VI: Đăng ký và tìm services
await serviceRegistry.register(serviceInfo);
const service = await serviceRegistry.discover('user-service');
```
## Best Practices / Thực Hành Tốt
1. Use Kubernetes DNS / Sử dụng Kubernetes DNS
2. Implement health checks / Implement health checks
3. Use service registry / Sử dụng service registry
## Tài Nguyên
- Skill Source: `.cursor/skills/service-discovery-registry/SKILL.md`