---
alwaysApply: true
---
# Go Development Rules for Cursor AI

You are an expert in Go, microservices architecture, and clean backend development practices. When working with Go code in this project, you MUST follow these rules strictly.

## Architecture Patterns

- **ALWAYS** apply Clean Architecture by structuring code into handlers/controllers, services/use cases, repositories/data access, and domain models
- **ALWAYS** use domain-driven design principles where applicable
- **ALWAYS** prioritize interface-driven development with explicit dependency injection
- **ALWAYS** prefer composition over inheritance; favor small, purpose-specific interfaces
- **ALWAYS** ensure that all public functions interact with interfaces, not concrete types, to enhance flexibility and testability

## Project Structure

When organizing code, you MUST follow this structure:
- `cmd/`: application entrypoints
- `internal/`: core application logic (not exposed externally)
- `pkg/`: shared utilities and packages
- `api/`: gRPC/REST transport definitions and handlers
- `configs/`: configuration schemas and loading
- `test/`: test utilities, mocks, and integration tests

Group code by feature when it improves clarity and cohesion. Keep logic decoupled from framework-specific code.

## Code Quality Requirements

- **ALWAYS** write short, focused functions with a single responsibility
- **ALWAYS** check and handle errors explicitly, using wrapped errors for traceability: `fmt.Errorf("context: %w", err)`
- **NEVER** use global state; use constructor functions to inject dependencies
- **ALWAYS** leverage Go's context propagation for request-scoped values, deadlines, and cancellations
- **ALWAYS** use goroutines safely; guard shared state with channels or sync primitives
- **ALWAYS** defer closing resources and handle them carefully to avoid leaks

## Security and Resilience

- **ALWAYS** apply input validation and sanitization rigorously, especially on inputs from external sources
- **ALWAYS** use secure defaults for JWT, cookies, and configuration settings
- **ALWAYS** isolate sensitive operations with clear permission boundaries
- **ALWAYS** implement retries, exponential backoff, and timeouts on all external calls
- **ALWAYS** use circuit breakers and rate limiting for service protection
- Consider implementing distributed rate-limiting to prevent abuse across services (e.g., using Redis)

## Testing Requirements

- **ALWAYS** write unit tests using table-driven patterns and parallel execution
- **ALWAYS** mock external interfaces cleanly using generated or handwritten mocks
- **ALWAYS** separate fast unit tests from slower integration and E2E tests
- **ALWAYS** ensure test coverage for every exported function, with behavioral checks
- Use tools like `go test -cover` to ensure adequate test coverage

## Documentation Standards

- **ALWAYS** document public functions and packages with GoDoc-style comments
- **ALWAYS** provide concise READMEs for services and libraries
- **ALWAYS** enforce naming consistency and formatting with `go fmt`, `goimports`, and `golangci-lint`

## Observability with OpenTelemetry

- **ALWAYS** use OpenTelemetry for distributed tracing, metrics, and structured logging
- **ALWAYS** start and propagate tracing spans across all service boundaries (HTTP, gRPC, DB, external APIs)
- **ALWAYS** attach `context.Context` to spans, logs, and metric exports
- **ALWAYS** use `otel.Tracer` for creating spans and `otel.Meter` for collecting metrics
- **ALWAYS** record important attributes like request parameters, user ID, and error messages in spans
- **ALWAYS** use log correlation by injecting trace IDs into structured logs
- Export data to OpenTelemetry Collector, Jaeger, or Prometheus

## Tracing and Monitoring

- **ALWAYS** trace all incoming requests and propagate context through internal and external calls
- **ALWAYS** use middleware to instrument HTTP and gRPC endpoints automatically
- **ALWAYS** annotate slow, critical, or error-prone paths with custom spans
- Monitor application health via key metrics: request latency, throughput, error rate, resource usage
- Define SLIs (e.g., request latency < 300ms) and track them with Prometheus/Grafana dashboards
- Alert on key conditions (e.g., high 5xx rates, DB errors, Redis timeouts) using a robust alerting pipeline
- **NEVER** create excessive cardinality in labels and traces; keep observability overhead minimal
- **ALWAYS** use log levels appropriately (info, warn, error) and emit JSON-formatted logs for ingestion by observability tools
- **ALWAYS** include unique request IDs and trace context in all logs for correlation

## Performance

- Use benchmarks to track performance regressions and identify bottlenecks
- Minimize allocations and avoid premature optimization; profile before tuning
- Instrument key areas (DB, external calls, heavy computation) to monitor runtime behavior

## Concurrency and Goroutines

- **ALWAYS** ensure safe use of goroutines, and guard shared state with channels or sync primitives
- **ALWAYS** implement goroutine cancellation using context propagation to avoid leaks and deadlocks

## Tooling and Dependencies

- **ALWAYS** rely on stable, minimal third-party libraries; prefer the standard library where feasible
- **ALWAYS** use Go modules for dependency management and reproducibility
- **ALWAYS** version-lock dependencies for deterministic builds
- **ALWAYS** integrate linting, testing, and security checks in CI pipelines

## Key Conventions

1. **ALWAYS** prioritize readability, simplicity, and maintainability
2. **ALWAYS** design for change: isolate business logic and minimize framework lock-in
3. **ALWAYS** emphasize clear boundaries and dependency inversion
4. **ALWAYS** ensure all behavior is observable, testable, and documented
5. **ALWAYS** automate workflows for testing, building, and deployment
# Go Development Rules for Cursor AI

You are an expert in Go, microservices architecture, and clean backend development practices. When working with Go code in this project, you MUST follow these rules strictly.

## Architecture Patterns

- **ALWAYS** apply Clean Architecture by structuring code into handlers/controllers, services/use cases, repositories/data access, and domain models
- **ALWAYS** use domain-driven design principles where applicable
- **ALWAYS** prioritize interface-driven development with explicit dependency injection
- **ALWAYS** prefer composition over inheritance; favor small, purpose-specific interfaces
- **ALWAYS** ensure that all public functions interact with interfaces, not concrete types, to enhance flexibility and testability

## Project Structure

When organizing code, you MUST follow this structure:
- `cmd/`: application entrypoints
- `internal/`: core application logic (not exposed externally)
- `pkg/`: shared utilities and packages
- `api/`: gRPC/REST transport definitions and handlers
- `configs/`: configuration schemas and loading
- `test/`: test utilities, mocks, and integration tests

Group code by feature when it improves clarity and cohesion. Keep logic decoupled from framework-specific code.

## Code Quality Requirements

- **ALWAYS** write short, focused functions with a single responsibility
- **ALWAYS** check and handle errors explicitly, using wrapped errors for traceability: `fmt.Errorf("context: %w", err)`
- **NEVER** use global state; use constructor functions to inject dependencies
- **ALWAYS** leverage Go's context propagation for request-scoped values, deadlines, and cancellations
- **ALWAYS** use goroutines safely; guard shared state with channels or sync primitives
- **ALWAYS** defer closing resources and handle them carefully to avoid leaks

## Security and Resilience

- **ALWAYS** apply input validation and sanitization rigorously, especially on inputs from external sources
- **ALWAYS** use secure defaults for JWT, cookies, and configuration settings
- **ALWAYS** isolate sensitive operations with clear permission boundaries
- **ALWAYS** implement retries, exponential backoff, and timeouts on all external calls
- **ALWAYS** use circuit breakers and rate limiting for service protection
- Consider implementing distributed rate-limiting to prevent abuse across services (e.g., using Redis)

## Testing Requirements

- **ALWAYS** write unit tests using table-driven patterns and parallel execution
- **ALWAYS** mock external interfaces cleanly using generated or handwritten mocks
- **ALWAYS** separate fast unit tests from slower integration and E2E tests
- **ALWAYS** ensure test coverage for every exported function, with behavioral checks
- Use tools like `go test -cover` to ensure adequate test coverage

## Documentation Standards

- **ALWAYS** document public functions and packages with GoDoc-style comments
- **ALWAYS** provide concise READMEs for services and libraries
- **ALWAYS** enforce naming consistency and formatting with `go fmt`, `goimports`, and `golangci-lint`

## Observability with OpenTelemetry

- **ALWAYS** use OpenTelemetry for distributed tracing, metrics, and structured logging
- **ALWAYS** start and propagate tracing spans across all service boundaries (HTTP, gRPC, DB, external APIs)
- **ALWAYS** attach `context.Context` to spans, logs, and metric exports
- **ALWAYS** use `otel.Tracer` for creating spans and `otel.Meter` for collecting metrics
- **ALWAYS** record important attributes like request parameters, user ID, and error messages in spans
- **ALWAYS** use log correlation by injecting trace IDs into structured logs
- Export data to OpenTelemetry Collector, Jaeger, or Prometheus

## Tracing and Monitoring

- **ALWAYS** trace all incoming requests and propagate context through internal and external calls
- **ALWAYS** use middleware to instrument HTTP and gRPC endpoints automatically
- **ALWAYS** annotate slow, critical, or error-prone paths with custom spans
- Monitor application health via key metrics: request latency, throughput, error rate, resource usage
- Define SLIs (e.g., request latency < 300ms) and track them with Prometheus/Grafana dashboards
- Alert on key conditions (e.g., high 5xx rates, DB errors, Redis timeouts) using a robust alerting pipeline
- **NEVER** create excessive cardinality in labels and traces; keep observability overhead minimal
- **ALWAYS** use log levels appropriately (info, warn, error) and emit JSON-formatted logs for ingestion by observability tools
- **ALWAYS** include unique request IDs and trace context in all logs for correlation

## Performance

- Use benchmarks to track performance regressions and identify bottlenecks
- Minimize allocations and avoid premature optimization; profile before tuning
- Instrument key areas (DB, external calls, heavy computation) to monitor runtime behavior

## Concurrency and Goroutines

- **ALWAYS** ensure safe use of goroutines, and guard shared state with channels or sync primitives
- **ALWAYS** implement goroutine cancellation using context propagation to avoid leaks and deadlocks

## Tooling and Dependencies

- **ALWAYS** rely on stable, minimal third-party libraries; prefer the standard library where feasible
- **ALWAYS** use Go modules for dependency management and reproducibility
- **ALWAYS** version-lock dependencies for deterministic builds
- **ALWAYS** integrate linting, testing, and security checks in CI pipelines

## Key Conventions

1. **ALWAYS** prioritize readability, simplicity, and maintainability
2. **ALWAYS** design for change: isolate business logic and minimize framework lock-in
3. **ALWAYS** emphasize clear boundaries and dependency inversion
4. **ALWAYS** ensure all behavior is observable, testable, and documented
5. **ALWAYS** automate workflows for testing, building, and deployment
